Leetcode: reorder-list
Given a singly linked list L: L 0→L 1→…→L n-1→L
n,
reorder it to: L 0→L n
→L 1→L n-1→L 2→L
n-2→…
You must do this in-place without alteringthe nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
思路:首先将链表一分为2,然后将后半链表反转之后,再插入前链表。
代码如下:
void reorderList(ListNode *head) {
if(!head || !head->next)
return;
stack<ListNode*> S;
ListNode* ctr = head;
ListNode* ptr = head->next;
while(ptr && ptr->next)
{
ctr = ctr->next;
ptr = ptr->next->next;
}
ListNode* hlp = ctr->next;
ctr->next = NULL;
while(hlp)
{
S.push(hlp);
hlp = hlp->next;
}
ctr = head;
while(!S.empty())
{
hlp = S.top();
S.pop();
hlp->next = ctr->next;
ctr->next = hlp;
ctr = hlp->next;
}
}