转载请注明出处:http://blog.csdn.net/ns_code/article/details/25737023
本文分别用非递归和递归两种方式实现了链表的反转,在九度OJ上AC。
题目描写叙述:
输入一个链表,反转链表后,输出链表的全部元素。(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 非常明显,翻转后,尾节点和头结点互换了。我们须要设置三个指针,分别指向当前要反转的节点、当前要反转节点的前一个节点、当前要反转节点的下一个节点。要注意链表为空,以及仅仅有一个头结点的情况。
非递归实现例如以下:
/* 反转链表,返回翻转后的头结点 */ pNode ReverseList(pNode pHead) { if(pHead == NULL) return NULL; if(pHead->next == NULL) return pHead; pNode pCur = pHead; pNode pPre = NULL; while(pCur != NULL) { pNode pNext = pCur->next; pCur->next = pPre; pPre = pCur; pCur = pNext; } return pPre; } 递归实现例如以下:
/* 递归实现反转链表,返回翻转后的头结点 */ pNode ReverseListRecursivly(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 pNewHead = ReverseListRecursivly(pCur,pNext); return pNewHead; } pNode ReverseList2(pNode pHead) { return ReverseListRecursivly(NULL,pHead); } 依据题目要求,測试代码例如以下:
int main() { int n; while(scanf("%d",&n) != EOF) { pNode pHead = NULL; if(n > 0) { int i,data; scanf("%d",&data); pHead =(pNode)malloc(sizeof(Node)); if(pHead == NULL) exit(EXIT_FAILURE); pHead->data = data; pHead->next = NULL; pNode pCur = pHead; for(i=0;i<n-1;i++) { scanf("%d",&data); pNode pNew =(pNode)malloc(sizeof(Node)); if(pNew == NULL) exit(EXIT_FAILURE); pNew->data = data; pNew->next = NULL; pCur->next = pNew; pCur = pCur->next; } } pNode pNewHead = ReverseList2(pHead); if(pNewHead == NULL) printf("NULL\n"); else { pNode pCur = pNewHead; while(pCur != NULL) { //这里主要时要注意输出的格式 if(pCur->next == NULL) printf("%d\n",pCur->data); else printf("%d ",pCur->data); pCur = pCur->next; } } } return 0; } /************************************************************** Problem: 1518 User: mmc_maodun Language: C Result: Accepted Time:150 ms Memory:2364 kb ****************************************************************/
转载于:https://www.cnblogs.com/bhlsheji/p/4015141.html