求解一道题~~
题目:建立一个链表,数据从键盘读取,链表的首结点由head返回。(要求运行输入1 2 3 4 5,输出5 4 3 2 1)。
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof( struct Node )
struct Node
{
int num;
struct Node *next;
};
struct Node *create()
{
struct Node *head, *p, *q;
int x;
head = (struct Node *)malloc(LEN);
head-> next = NULL;
p = head;
scanf( "%d ", &x );
while ( x != 0 )
{
q = (struct Node *)malloc(LEN);
q-> num = x;
q-> next = NULL;
p-> next = q;
p = q;
scanf( "%d ", &x );
}
return ( head );
}
struct Node *reverse(struct Node *head)
{
struct Node *p, *q;
p = head-> next;
head-> next = NULL;
while ( p != NULL)
{
q = p;
p = p-> next;
q-> next = head-> next;
head-> next = q;
}
return head;
}
void Print( struct Node *head )
{
struct Node *p;
p = head-> next;
while ( p != NULL )
{
printf( "%-2d ", p-> num );
p = p-> next;
}
}
int main()
{
struct Node *head;
printf( "Please input a array of number with 0 end\n " );
head = create();
printf( "output the link after reversed as follow\n " );
head = reverse(head);
Print( head );
printf( "\n " );
system( "pause " );
return 0;
}
输入:1 2 3 4 5 0 <enter>
输出:5 4 3 2 1