剑指offer——面试题16:反转链表
2018-03-11 23:24
393 查看
剑指offer——面试题16:反转链表
牛客网上有《剑指offer》的题目训练https://www.nowcoder.com/activity/oj一个有关此题图文并茂的博客:http://blog.csdn.net/fx677588/article/details/72357389,有助于理解递归版的代码!!!
递归版本代码的参考网址:http://blog.csdn.net/yunzhongguwu005/article/details/10350339
1.常规思路代码
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { ListNode* pReverseHead = NULL; //反序链表表头,初始化为空 ListNode* pNode = pHead; //当前结点 ListNode* pPrev = NULL; //原链表中当前结点的前一个结点,初始化为空 while(pNode != NULL){ ListNode* pNext = pNode->next;//原链表中当前结点的下一个结点 if(pNext == NULL) pReverseHead = pNode; //若下一个结点为空,则该结点就是反序链表表头 pNode->next = pPrev;//原前一个结点变为当前结点的后继结点 pPrev = pNode;//当前结点变为前序结点 pNode = pNext;//当前结点更新 } return pReverseHead; } };
2.递归版代码
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { //如果链表为空或者链表中只有一个元素 if(pHead == NULL || pHead->next == NULL) //链表为空直接返回,而head->next为空是递归基 return pHead; else { ListNode* newhead = ReverseList(pHead->next);//先反转后面的链表 pHead->next->next = pHead;//再将当前节点设置为其然来后面节点的后续节点 pHead->next = NULL; //记得赋值NULL,防止链表错乱 return newhead; //新链表头永远指向的是原链表的链尾 } } };
相关文章推荐
- 【剑指Offer】面试题16:反转链表
- 【剑指offer】面试题16、反转链表
- [剑指offer]面试题16:反转链表
- 剑指offer面试题16之反转链表
- 剑指offer 面试题16:反转链表(Leetcode 206: Reverse Linked List) 题解
- 剑指offer——面试题16:反转链表
- 剑指offer-面试题16-反转链表
- 【剑指offer】面试题16:反转链表
- 剑指offer面试题16:反转链表
- 剑指Offer:面试题16——反转链表(java实现)
- 剑指Offer----面试题16:反转链表
- 剑指offer之面试题16 :反转链表
- 剑指offer-chapter3-面试题16-反转链表(java)
- 剑指Offer---面试题16:反转链表
- 剑指offer:面试题16 反转链表
- 剑指offer_面试题16_反转链表(两种方法)
- 【剑指offer 面试题16】反转链表
- 剑指offer-面试题16-反转链表
- 【剑指offer】面试题16:反转链表
- 剑指offer面试题16——反转链表