首页 > 代码库 > [LeetCode] Reorder List

[LeetCode] Reorder List

Given a singly linked list L: L0L1→…→Ln-1Ln, reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes‘ values.

For example, Given {1,2,3,4}, reorder it to {1,4,2,3}.

/** * 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) {        ListNode *p1=head,*p2=head,*pre;        while(p2!=NULL && p2->next!=NULL)//找到后一半的开头节点head2;        {          pre = p1;          p1 = p1->next;          p2 = p2->next;          p2 = p2->next;        }                if(p1 == p2)            return;        pre->next = NULL;//前一半的结尾标记        ListNode *head2 = p1;               stack<ListNode*> st;       while(head2)       {         st.push(head2);         head2 = head2->next;       }       p1 = head;       ListNode *ph1,*ph2;       while(p1 && !st.empty() )       {         ph1 = p1->next;         ph2 = st.top();         st.pop();         p1->next = ph2;         ph2->next = ph1;         p1 = ph1;              }       if(!st.empty())       {         ph1 = st.top();         ph1->next = NULL;         st.pop();         ph2->next = ph1;              }    }};

(1)注意数据结构用stack比较方便,如果用遍历的方法,则会超时Time Limited Exceeded!
 (2)测试用例中,head包括NULL,1个结点、2个结点、3个结点、4个结点,把这几个测试正确,其余的应该就没有问题了。