LeetCode OJ:Reorder List(重序链表)
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
如上例子所示的重序链表问题,先找到中间节点,然后将链表分成两段。将第二段反转后依次插入第一段中就得到了完整的链表,代码如下所示:
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 void reorderList(ListNode* head) { 12 if(!head || !head->next) return; 13 ListNode * fastNode = head, * slowNode = head; 14 while(fastNode->next){ 15 fastNode = fastNode->next; 16 if(fastNode->next){ 17 slowNode = slowNode->next; 18 fastNode = fastNode->next; 19 } 20 } 21 ListNode * p1 = head; 22 ListNode * p2 = slowNode->next; 23 slowNode->next = NULL;//将前一段链表的最后一个节点的下一个赋为值NULL 24 //将第二个节点指向的链表颠倒过来 25 ListNode * prev = NULL; 26 ListNode * curr = p2; 27 ListNode * tmpNode = NULL; 28 while(curr){ 29 tmpNode = curr->next; 30 curr->next = prev; 31 prev = curr; 32 curr = tmpNode; 33 } 34 p2 = prev;//颠倒之后的首节点 35 ListNode * tmpNode1, * tmpNode2; 36 while(p2){ 37 tmpNode1 = p1->next; 38 p1->next = p2; 39 tmpNode2 = p2->next; 40 p2->next = tmpNode1; 41 p1 = tmpNode1; 42 p2 = tmpNode2; 43 } 44 } 45 };
代码重复有点多,写的比较乱,见谅见谅。