【剑指offer】递归循环两种方式反转链表
http://blog.csdn.net/ns_code/article/details/25737023
转载请注明出处: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===================================================
- ActList* ReverseList2(ActList* head)
- {
- //ActList* temp=new ActList;
- if(NULL==head|| NULL==head->next) return head; //少于两个节点没有反转的必要。
- ActList* p;
- ActList* q;
- ActList* r;
- p = head;
- q = head->next;
- head->next = NULL; //旧的头指针是新的尾指针,next需要指向NULL
- while(q){
- r = q->next; //先保留下一个step要处理的指针
- q->next = p; //然后p q交替工作进行反向
- p = q;
- q = r;
- }
- head=p; // 最后q必然指向NULL,所以返回了p作为新的头指针
- return head;
- }
浙公网安备 33010602011771号