数据结构C/C++高手帮忙
解决时间 2021-06-04 00:14
- 提问者网友:战皆罪
- 2021-06-03 16:51
一,输入一个数列,以0为结束,生成单链表。(输入顺序与结点顺序一致。)
二,输出表中结点。
三,逆转表中结点并输出。
四,按升序排序结点并输出。
五,释放结点空间。
帮忙一下我C语言初学者啊。
最佳答案
- 五星知识达人网友:蓝房子
- 2021-06-03 17:21
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct _list {
int val;
struct _list* next;
} *node, list;
node Insert( node* head, node pos, int val )
{
node tmp;
tmp = ( node )malloc( sizeof( list ) );
tmp->val = val;
tmp->next = pos ? pos->next : *head;
if ( pos ) {
pos->next = tmp;
} else {
*head = tmp;
}
return tmp;
}
node Create( void )
{
node head, t;
int n;
head = t = NULL;
while ( scanf( "%d", &n ) && n != 0 ) {
t = Insert( &head, t, n );
}
return head;
}
void Reverse( node* head )
{
node prev, next, tmp;
prev = *head;
next = prev->next;
while ( next ) {
tmp = next->next;
next->next = prev;
prev = next;
next = tmp;
}
(*head)->next = NULL;
*head = prev;
}
void Print( node head )
{
while ( head ) {
printf( "%d ", head->val );
head = head->next;
}
putchar( '\n' );
}
node msort( node* head, int n )
{
int i, m;
node l, r, p, *x, *y;
if ( n < 2 ) return *head;
m = n/2;
p = l = r = *head;
for ( i = m; i > 0; --i )
p = r, r = r->next;
p->next = NULL;
l = msort( &l, m );
r = msort( &r, n - m );
x = &p;
while ( l && r ) {
*x = l->val < r->val ? (y = &l, l) : (y = &r, r);
*y = (*y)->next; x = &(*x)->next;
}
l = l ? l : r ? r : NULL;
*x = l; *head = p;
return p;
}
void Sort( node* head )
{
int i;
node tmp = *head;
for ( i = 0; tmp; ++i, tmp = tmp->next );
msort( head, i );
}
void Del( node head )
{
node tmp;
while ( head ) {
tmp = head;
head = head->next;
free( tmp );
}
}
int main( void )
{
node head = Create();
Print( head );
Reverse( &head );
Print( head );
Sort( &head );
Print( head );
Del( head );
getch();
return 0;
}
我要举报
大家都在看
推荐资讯