leetcode143. Reorder List
题意:
给定单链表L:L0≤L1≤... Ln-1≤Ln,
将其重新排序为:L0≤Ln≤L1≤Ln-1≤L2≤Ln-2≤...
思路:
第一次遍历把数组切成两半,然后吧右边的reverse,然后连接两个list,注意细节
ac代码:
C++
/**
* 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 || !head->next) return;
ListNode* slow = head;
ListNode* fast = head->next;
//find middle,cut list
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = slow->next;
slow->next = NULL;
//reverse right part
ListNode* p2 = head2->next;
head2->next = NULL;
ListNode* p1 = p2;
while(p2)
{
p1 = p2->next;
p2->next = head2;
head2 = p2;
p2 = p1;
}
for(p1 = head,p2 = head2;p1;)
{
auto t = p1->next;
p1 = p1->next = p2;
p2 = t;
}
}
};
python