35 翻转链表

原题网址:http://www.lintcode.com/zh-cn/problem/reverse-linked-list/#

翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

挑战 

在原地一次翻转完成

标签 
 
思路:new一个尾节点,其数值等于head数值,遍历head,从后向前挂载节点。
 
 1 /**
 2  * Definition of singly-linked-list:
 3  *
 4  * class ListNode {
 5  * public:
 6  *     int val;
 7  *     ListNode *next;
 8  *     ListNode(int val) {
 9  *        this->val = val;
10  *        this->next = NULL;
11  *     }
12  * }
13  */
14 
15 class Solution {
16 public:
17     /**
18      * @param head: n
19      * @return: The new head of reversed linked list.
20      */
21     ListNode * reverse(ListNode * head) {
22         // write your code here
23         if (head==NULL)
24      {
25          return head;
26      }
27 
28      ListNode *tail=new ListNode(head->val);
29      
30      while(head->next!=NULL)
31      {
32          head=head->next;
33          ListNode *newNode=new ListNode(head->val);
34          newNode->next=tail;
35          tail=newNode;
36      }
37 
38      return tail;
39     }
40 };

挑战,原地一次翻转。

刚开始抓破头皮想不到,后来上网搜了下参照了别人的想法码了出来,链接:https://www.cnblogs.com/lelelelele/p/6109949.html

具体思路:
设置三根指针分别指向翻转后的当前节点,前置节点,与后继节点。
当前节点cur不为空时,pre=cur->next(保存下次要处理的节点)。
接下来curNode->next=nextNode与nextNode=curNode,当前节点与原链表断开,其后继节点为上次循环的cur(画个图就明白了,或者看上面链接)。
然后是curNode=preNode,这句的意思是移动到原链表下个节点,判断是否进入下次循环。
循环结束时,cur与pre都为NULL,要返回上次的cur(原链表的尾节点),即nextNode。
 
PS:其实普通单链表的挂载只需要知道当前节点和后继节点就可以了,本题设置pre是为了移动遍历原链表。
 
 1 /**
 2  * Definition of singly-linked-list:
 3  *
 4  * class ListNode {
 5  * public:
 6  *     int val;
 7  *     ListNode *next;
 8  *     ListNode(int val) {
 9  *        this->val = val;
10  *        this->next = NULL;
11  *     }
12  * }
13  */
14 
15 class Solution {
16 public:
17     /**
18      * @param head: n
19      * @return: The new head of reversed linked list.
20      */
21     ListNode * reverse(ListNode * head) {
22         // write your code here
23          if (head==NULL)
24      {
25          return head;
26      }
27 
28      //挑战:原地翻转;
29     ListNode *curNode=head;
30     ListNode *preNode=NULL;
31     ListNode *nextNode=NULL;
32     while(curNode!=NULL)
33     {
34         preNode=curNode->next;
35         curNode->next=nextNode;
36         nextNode=curNode;
37         curNode=preNode;    
38     }
39     
40     return nextNode;
41     }
42 };
原文地址:https://www.cnblogs.com/Tang-tangt/p/8709167.html