Problem:
Given a singly linked listL:L0→L1→... →L N-1→LN,
Reorder it to:L0→LN→L1→L N-1→L2→L N-2→...
You must does this in-place without altering the nodes ' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
Hide TagsLinked ListTest instructions: Reorder the single-linked list, and then insert the tail node behind the head node in turn.
Thinking:
(1) because the single-linked list has only one next pointer, you need to use the stack to store node pointers.
(2) Each time the top node of the stack is inserted behind the head node of a single linked list, modify the relevant pointer, and the head pointer traverses backwards
(3) The straight head pointer equals the top element of the stack (the single-linked list node is odd) or the next node of the head pointer is the top element of the stack (the total is even), stopping the traversal
, place the last node next pointer empty
Code: Time complexity O (n)
Class Solution {public : void Reorderlist (listnode* head) { stack<listnode *> _stack; ListNode *tmp=head; while (Tmp!=null) { _stack.push (TMP); tmp=tmp->next; } if (_stack.size () <3) return; ListNode *p= head; ListNode *q=_stack.top (); while (p!=q && p->next!=q) { _stack.pop (); ListNode *p_next=p->next; p->next=q; q->next=p_next; P=p_next; Q=_stack.top (); } q->next=null; } };
Leetcode | | 143. Reorder List