143. 重排链表

 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 //1、快慢指针找中间结点
10 //2、后半段逆序
11 //3、拼接
12 class Solution 
13 {
14 public:
15     void reorderList(ListNode* head) 
16     {
17         ListNode* fast = head;
18         ListNode* slow = head;
19         while(fast && fast->next && slow)
20         {
21             fast = fast->next->next;
22             slow = slow->next;
23         }
24 
25         ListNode* new_node = NULL;
26         while(slow)
27         {
28             ListNode* temp = slow->next;
29             slow->next = new_node;
30             new_node = slow;
31             slow = temp;
32         }
33 
34         ListNode* a = head;
35         ListNode* dummy = new ListNode(-1);
36         ListNode* pre = dummy;
37         while(head && new_node)
38         {
39             pre->next = head;
40             head = head->next;
41             pre = pre->next;
42 
43             pre->next = new_node;
44             new_node = new_node->next;
45             pre = pre->next;
46         }
47         if(new_node != NULL)
48         {
49             pre->next = new_node;
50             new_node->next = NULL;
51         }
52         dummy->next = head;
53     }
54 };

 

上一篇:143. 重排链表


下一篇:104. 货仓选址