首页 > 其他 > 详细

143. 重排链表

时间:2020-04-02 20:22:05      阅读:54      评论:0      收藏:0      [点我收藏+]
 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. 重排链表

原文:https://www.cnblogs.com/yuhong1103/p/12622316.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!