您的位置:首页 > 其它

143. Reorder List LeetCode

2016-03-17 22:26 477 查看
题意:给你一个链表,把链表从 L: L0→L1→…→Ln-1→Ln,变成L0→Ln→L1→Ln-1→L2→Ln-2→…。

题解:把链表的后一般翻转,然后两个链表按规则合并。

class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre = NULL;
ListNode *cur = head;
while(cur != NULL)
{
ListNode *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
void reorderList(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
if(!fast || !fast->next) return;
while(fast)
{
fast = fast->next;
if(fast) fast = fast->next;
else break;
slow = slow->next;
}
ListNode* re = slow->next;
slow->next = NULL;
ListNode* nxt = reverseList(re);
ListNode* pre = head;
while(pre && nxt)
{
ListNode* tmp = pre->next;
pre->next = nxt;
nxt = nxt->next;
pre->next->next = tmp;
pre = tmp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode