66-Reorder List

  1. Reorder List My Submissions QuestionEditorial Solution
    Total Accepted: 64392 Total Submissions: 281830 Difficulty: Medium
    Given a singly linked list L: L0→L1→…→Ln-1→Ln,
    reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.

思路:
1.找到中点,前半部分最后一个点
a.找到后半部分第一个点
b.后半部分入栈
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) {
        int len=0;
        if(head==NULL||head->next==NULL)return;
        if(head->next->next==NULL)return;
        ListNode *p=head,*fir_end,*sec_beg;
        while(p){
            len++;
            p = p->next;
        }
        int mid=(len%2==0)?len/2:len/2+1;
        mid = mid -1;
        fir_end = head;
        while(mid--){
            fir_end=fir_end->next;
        }
        sec_beg = fir_end->next;
        stack<ListNode*> slist;
        while(sec_beg!=NULL){
            slist.push(sec_beg);
            sec_beg = sec_beg->next;
        }
        while(!slist.empty()){  //如果栈中有元素未被链接起来
            ListNode *tmp=head->next,*stop=slist.top(); //保存前半部分当前节点下一个节点
            head->next = stop;   //链接栈中元素
            stop->next = tmp;    //栈中元素链接到原来当前节点的下一元素,相当于在中间插入
            slist.pop(); 
            head = tmp;
        }
        if(head!=NULL)head->next = NULL;//如果链长为奇数,最后一个元素指向空
    }
};

你可能感兴趣的:(list,reorder)