LeetCode | Reorder List
2013-12-10 15:47
309 查看
题目:
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}.
思路:
利用快慢两个指针将链表一分为二,针对第二个子链表求倒序,最后将两个子链表合并。
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode *head) { ListNode * slow=head; ListNode * fast=head; if(head != NULL && head->next != NULL) { while(fast!=NULL && fast->next != NULL) { slow=slow->next; fast=fast->next->next; } ListNode * tmp = slow->next; slow->next = NULL; ListNode * p2= head; ListNode * p1 =NULL; while(tmp!=NULL) { ListNode* t = p1; p1=tmp; tmp=tmp->next; p1->next = t; } tmp =NULL; while(p1!=NULL && p2!=NULL) { if(tmp==NULL) { tmp=p2; } else { tmp->next = p2; tmp=tmp->next; } p2=p2->next; tmp->next =p1; p1=p1->next; tmp=tmp->next; tmp->next = NULL; } if(p1!=NULL) { if(tmp==NULL) { tmp=p1; } else { tmp->next=p1; } } if(p2!=NULL) { if(tmp==NULL) { tmp=p2; } else { tmp->next=p2; } } } } };
重新优化之后
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode *head) { if(head == NULL){ return; } ListNode* p1 = head; ListNode* p2 = splitList(head); p2 = revertList(p2); mergeList(p1, p2); } void mergeList(ListNode * p1, ListNode * p2){ while(p2 != NULL){ ListNode* tmp = p2; p2 = p2->next; tmp->next = p1->next; p1->next = tmp; p1 = p1->next; p1 = p1->next; }; } ListNode* splitList(ListNode *head){ ListNode* slow = new ListNode(0); slow->next = head; ListNode* fast = slow; while(fast->next != NULL && fast->next->next != NULL){ slow = slow->next; fast = fast->next; fast = fast->next; } if(fast->next != NULL){ slow = slow->next; fast = fast->next; } ListNode* tmp = slow->next; slow->next = NULL; return tmp; } ListNode* revertList(ListNode* head){ if(head == NULL){ return NULL; } ListNode* p = head->next; head->next = NULL; while(p != NULL){ ListNode* tmp = p; p = p->next; tmp->next = head; head = tmp; } return head; } };
相关文章推荐
- leetcode || 143、Reorder List
- leetCode刷题Reorder_list (快速求出链表的中间结点——快慢指针方法)
- LeetCode Reorder List
- [leetcode 143] Reorder List
- 【leetcode】Reorder List (python)
- LeetCode -- Reorder List
- [LeetCode]Reorder List 链表重排序
- [LeetCode]Reorder List
- Leetcode Reorder List 143
- 【LeetCode】Reorder List
- leetcode:Reorder List
- Leetcode-Reorder List
- leetcode 【 Reorder List 】python 实现
- [LeetCode]题解(python):143-Reorder List
- 【leetcode】【单链表】【143】Reorder List
- leetcode 日经贴,Cpp code -Reorder List
- LeetCode-Reorder List
- leetcode之reorder-list
- 143. Reorder List LeetCode
- Leetcode: Reorder List