Leetcode- 143. Reorder List
2017-01-24 10:08
246 查看
解题思路:使用快慢指针找到链表的中间位置(代码需要写的非常小心)。对于后半部分的链表逆序(如果不使用哑节点dummy方法,需要在之前判断链表元素个数小于1时直接返回。)
/**
* 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 || head->next==NULL)
return;
ListNode *slow=head,*fast=head->next;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
ListNode *newh = slow->next;
slow->next = NULL;
fast = newh->next;
newh->next =NULL;
while(fast){
ListNode *tmp = fast->next;
fast->next = newh;
newh = fast;
fast = tmp;
}
ListNode *cur = head;
while(cur && newh){
ListNode *post = cur->next;
ListNode *tmp = newh;
newh = newh->next;
cur->next = tmp;
tmp->next = post;
cur = post;
}
}
};
/**
* 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 || head->next==NULL)
return;
ListNode *slow=head,*fast=head->next;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
}
ListNode *newh = slow->next;
slow->next = NULL;
fast = newh->next;
newh->next =NULL;
while(fast){
ListNode *tmp = fast->next;
fast->next = newh;
newh = fast;
fast = tmp;
}
ListNode *cur = head;
while(cur && newh){
ListNode *post = cur->next;
ListNode *tmp = newh;
newh = newh->next;
cur->next = tmp;
tmp->next = post;
cur = post;
}
}
};
相关文章推荐
- [LeetCode] 143. Reorder List
- LeetCode143. Reorder List
- Leetcode 143. Reorder List
- 【Leetcode】143. Reorder List
- leetcode ---- 143. Reorder List
- LeetCode 143. Reorder List
- [leetcode]143. Reorder List -- JavaScript 代码
- LeetCode 143. Reorder List
- leetcode 143. Reorder List
- 【LeetCode】 143. Reorder List
- LeetCode 143. Reorder List
- [Leetcode] 143. Reorder List 解题报告
- Leetcode-143. Reorder List
- [leetcode] 143. Reorder List 解题报告
- [leetcode]143. Reorder List
- [LeetCode] 143. Reorder List
- 【Leetcode】143. Reorder List - 链表重排序
- *Leetcode 143. Reorder List | 链表
- [LeetCode]143. Reorder List
- leetcode143. Reorder List