LeetCode Reverse Linked List (反置链表)

 

LeetCode Reverse Linked List (反置链表)_第1张图片

题意:如标题

思路:将链表扫一遍复制出val,然后再一遍,反向赋值回去。

 

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         vector<int> vect;
13         ListNode* c=head;
14         while(c)
15         {
16             vect.push_back(c->val);
17             c=c->next;
18         }
19         c=head;
20         for(int i=vect.size()-1; i>=0; i--)
21         {
22             c->val=vect[i];
23             c=c->next;
24         }
25         return head;
26     }
27 };
AC代码

 

 

 

递归思路:返回值为原链表尾,在返回之前要使后继指向前驱,那么后继的后继没有人记住了,要弄个临时变量记住。

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* give_me_your_son( ListNode* far, ListNode* son)
12     {
13         if(!son)    return far;     //far就是链表尾了
14         ListNode* tmp=son->next;
15         son->next=far;
16         return give_me_your_son( son, tmp);
17     }
18 
19     ListNode* reverseList(ListNode* head) {
20         if(!head||!head->next)   return head;
21         return give_me_your_son(0,head);
22     }
23 };
AC代码

 

你可能感兴趣的:(LeetCode)