Reorder List

来源:互联网 发布:什么天气软件最准确 编辑:程序博客网 时间:2024/06/06 03:40

Description:

Given a singly linked list L : L 0 → L 1 → · · · → L n−1 → L n , reorder it to: L 0 → L n → L 1 →
L n−1 → L 2 → L n−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}.

分析:
题目规定要 in-place,也就是说只能使用 O(1) 的空间。
可以找到中间节点,断开,把后半截单链表 reverse 一下,再合并两个单链表。

#include <iostream>#include <limits.h>using namespace std;struct LNode{    int val;    LNode *next;    LNode(int x):val(x),next(nullptr) {}};class Solution{    public:        LNode *reorderList(LNode *L)        {            if (L == nullptr || L->next == nullptr)                return L;            LNode *slow = L, *fast = L;            LNode *prev = nullptr;            while (fast && fast->next)            {                prev = slow;                slow = slow->next;                fast = fast->next->next;            }            prev->next = nullptr;            slow = reverseList(slow);            //merge two lists            LNode *p1 = L, *p2 = slow;            LNode *p1Next = nullptr, *p2Next = nullptr;            while (p1->next)            {                p1Next = p1->next;                p2Next = p2->next;                p2->next = p1->next;                p1->next = p2;                p1 = p1Next;                p2 = p2Next;            }            p1->next = p2;            return L;        }        LNode *reverseList(LNode *List)        {            LNode *head = List;            LNode *pre = List;            LNode *cur = pre->next;            LNode *curNext = nullptr;            while (cur)            {                curNext = cur->next;                cur->next = pre;                pre = cur;                cur = curNext;            }            head->next = nullptr;            return pre;        }};int main(){    LNode *List = new LNode(INT_MIN); // create head node    cout<<"Input the number: "<<endl;    int n;    cin>>n;    LNode *ptr = List;    for (int i = 1; i <= n; ++i)    {        ptr->next = new LNode(i);        ptr = ptr->next;        cout<<ptr->val;        if (i < n)            cout<<"->";    }    cout<<endl;    Solution solution;    LNode *result = solution.reorderList(List->next);    delete List; // release    ptr = result;    while (result) // output and release the list    {        ptr = result->next;        cout<<result->val;        if (ptr)            cout<<"->";        delete result;        result = ptr;    }    cout<<endl;    return 0;}

这里写图片描述

这里写图片描述

0 0
原创粉丝点击