[leetcode] Reorder List

来源:互联网 发布:mac 下载不在dock 编辑:程序博客网 时间:2024/06/06 20:19

Reorder List

in-place:只能使用O(1)的空间;

思路:找到中间节点,断开单链表;逆置后半段链表;然后合并两端链表。


/** * 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) {        if(head==nullptr||head->next==nullptr){            return;        }        //使用快慢指针找到中间节点        ListNode *slow,*fast;        slow=fast=head;        ListNode *prev=nullptr;        while(fast&&fast->next){            prev=slow;            slow=slow->next;            fast=fast->next->next;        }        prev->next=nullptr;//断开        slow=reverse(slow);//逆置                ListNode *cur=head;        while(cur->next){            ListNode *tmp=cur->next;            cur->next=slow;            slow=slow->next;            cur->next->next=tmp;            cur=tmp;        }        cur->next=slow;    }        ListNode* reverse(ListNode *head){//单链表逆置        if(head==nullptr||head->next==nullptr){//空or单节点            return head;        }        ListNode *prev=nullptr;        ListNode *cur=head;        ListNode *tmp=prev;        while(cur!=nullptr){            tmp=prev;            prev=cur;            cur=cur->next;            prev->next=tmp;        }        return prev;    }};


0 0