输入一个链表,反转链表后,输出链表的所有元素。
(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
有递归和非递归两种方案.
/* 反转链表 by Rowandjj 2014/7/31 */ #include<stdio.h> #include<stdlib.h> typedef struct _NODE_ { int data; struct _NODE_ *next; }Node,*pNode,*List; void Create(List *list,int n) { if(n <= 0) { return; } int data; scanf("%d",&data); *list = (pNode)malloc(sizeof(Node)); if(*list == NULL) { exit(-1); } (*list)->data = data; (*list)->next = NULL; pNode pTemp = *list; for(int i = 0; i < n-1; i++) { pNode pNew = (pNode)malloc(sizeof(Node)); scanf("%d",&data);; if(!pNew) { exit(-1); } pNew->data = data; pNew->next = NULL; pTemp->next = pNew; pTemp = pNew; } } //反转链表,返回反转链表的头结点 //非递归 List reverseList(List list) { pNode pHead = NULL,pCur = list,pPre = NULL; while(pCur != NULL) { pNode pNext = pCur->next; if(pNext == NULL) { pHead = pCur; } pCur->next = pPre; pPre = pCur; pCur = pNext; } return pHead; } //递归 List reverseList_2(pNode pPre,pNode pCur) { if(pCur == NULL) { return NULL; } if(pCur->next == NULL) { pCur->next = pPre; return pCur; } pNode pNext = pCur->next; pCur->next = pPre; pNode pHead = reverseList_2(pCur,pNext); return pHead; } pNode reverse(pNode pHead) { return reverseList_2(NULL,pHead); } int main() { int n; while(scanf("%d",&n) != EOF) { List list = NULL; Create(&list,n); list = reverse(list); if(list == NULL) { printf("NULL\n"); } pNode pt = list; while(pt != NULL) { if(pt->next == NULL) printf("%d\n",pt->data); else printf("%d ",pt->data); pt = pt->next; } } return 0; }
原文:http://blog.csdn.net/chdjj/article/details/38322273