Leetcode No.143 **

给定一个单链表 LL0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→LnL1→Ln-1→L2→Ln-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

参考博客:http://www.cnblogs.com/grandyang/p/4254860.html

解答:可以采用压栈方式——先进后出来求解。将节点依次压入栈中,然后顺序取出即可,取栈次数为 st.size()/2。有个问题点需要注意,最后的节点需要在末尾处置null,否则会出现环形链表。

//143
void reorderList(ListNode* head)
{
    if(head==NULL || head->next==NULL) return;
    stack<ListNode*> st;
    ListNode* curr=head,*next;
    while(curr!=NULL) {st.push(curr);curr=curr->next;}
    curr=head;
    int cnt = st.size()/2;
    while(cnt--)
    {
        next = curr->next;
        curr->next=st.top();
        st.top()->next=next;
        st.pop();
        curr=next;
    }
    curr->next=NULL;
}//143
原文地址:https://www.cnblogs.com/2Bthebest1/p/10851472.html