-
题目描述:
-
输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)
-
输入:
-
输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。
-
输出:
-
对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。
-
样例输入:
-
5 1 2 3 4 5 0
-
样例输出:
-
5 4 3 2 1 NULL
-
/*将list逆序*/ #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct node { int data ; struct node * next ; }node , *list ; void Create(list &L) { L = (node *)malloc(sizeof(node)) ; L->next = NULL ; } void Insert(list &L , int e) { list p = L , s ; while(p->next) p=p->next; s = (node *)malloc(sizeof(node)) ; s->data = e ; s->next = NULL ; s->next = p->next ; p->next = s; } void Traver(list L , int n) { list p = L->next; while(p && n-- ){ printf("%d ",p->data); p=p->next ; } printf("%d\n",p->data); } void Reverse(list &L) { if(!L->next||!L->next->next) return ; list p = L->next; list q = p->next; list t = NULL ; while(q){ t = q->next; q->next = p ; p = q ; q = t ; } L->next->next = NULL ; L->next = p ; } int main(void) { int n ; while(scanf("%d",&n)!=EOF){ list L; L = (node *)malloc(sizeof(node)) ; Create(L); int i , cnt ; for( i = 0 ; i < n ; i ++) { scanf("%d",&cnt); Insert(L,cnt); } Reverse(L); if(n) Traver(L,n-1); else printf("NULL\n"); } return 0 ; }