您的位置:首页 > 其它

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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: