LeetCode 143. Reorder List
Posted co0oder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 143. Reorder List相关的知识,希望对你有一定的参考价值。
ver0:
最简单的思路,得到中间节点,把这之后的节点放入stack中,再从head开始,把stack.top()插入。
具体解释:得到slow后,分两种情况考虑,链表长度为偶,slow为前半段的最后一个节点;链表长度为奇,slow为正中间节点的前一个节点。两种情况下reoder后slow->next仍在原来的位置,因此因此mid = slow->next->next。
72ms
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 == NULL || head->next == NULL) return; 13 ListNode* slow = head, * fast = head->next; 14 while(fast->next && fast->next->next){ 15 slow = slow->next; 16 fast = fast->next->next; 17 } 18 ListNode* mid = slow->next->next; 19 slow->next->next = NULL; 20 stack<ListNode*> stk; 21 while(mid){ 22 stk.push(mid); 23 mid = mid->next; 24 } 25 ListNode* resH = head; 26 while(!stk.empty()){ 27 ListNode* tmp = resH->next; 28 resH->next = stk.top(); 29 resH->next->next = tmp; 30 stk.pop(); 31 resH = tmp; 32 } 33 34 35 } 36 };
以下两个算法均为64ms
ver1:
把所有节点放入vector,变量i、j从vector两头开始,进行链接。
1 class Solution { 2 public: 3 void reorderList(ListNode* head) { 4 vector<ListNode*> v; 5 ListNode* tmp = head ; 6 while( tmp ) { 7 v.push_back(tmp); 8 tmp = tmp->next; 9 } 10 for( int i=0, j=v.size()-1; i<=j; i++, j-- ) { 11 if( tmp ) tmp->next = v[i]; 12 v[i]->next = v[j]; 13 tmp = v[j]; 14 } 15 if( tmp ) tmp->next = NULL; 16 } 17 };
ver2:
得到链表的中点,把后半段链表reverse,然后前后两段链表merge。
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head){ 4 if (head==NULL || head->next==NULL) return head; 5 ListNode *pre=head, *cur=pre->next, *post; 6 pre->next = NULL; 7 while (cur!=NULL){ 8 post = cur->next; 9 cur->next = pre; 10 pre = cur; 11 cur = post; 12 } 13 return pre; 14 } 15 void mergeList(ListNode* L1, ListNode *L2){ 16 ListNode *cur1=L1, *cur2=L2,*post1,*post2; 17 while(cur2!=NULL){ 18 post1 = cur1->next; 19 post2 = cur2->next; 20 cur1->next = cur2; 21 cur2->next = post1; 22 cur1 = post1; 23 cur2 = post2; 24 } 25 } 26 void reorderList(ListNode* head) { 27 if (head==NULL || head->next==NULL || head->next->next==NULL) return; 28 ListNode *slow=head,*fast=head; 29 while(fast->next!=NULL && fast->next->next!=NULL){ 30 fast = fast->next->next; 31 slow = slow->next; 32 } 33 ListNode *head2 = slow->next; 34 slow->next = NULL; 35 mergeList(head,reverseList(head2)); 36 } 37 };
还有一种递归的算法,未看,留坑
https://leetcode.com/discuss/93197/concise-recursive-o-solution-with-space-easy-to-understand
以上是关于LeetCode 143. Reorder List的主要内容,如果未能解决你的问题,请参考以下文章