LeetCode-M-Reorder List

来源:互联网 发布:杭州汉聚网络招聘 编辑:程序博客网 时间:2024/06/05 07:33

题意

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}.

解法

用快慢指针找出后半段,翻转后半段,然后插入到前半段即可

实现

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head){        if(head == NULL || head->next == NULL) return head;        ListNode* cur = head;        while(cur->next != NULL){            ListNode* next = cur->next;            cur->next = next->next;            next->next = head;            head = next;        }        return head;    }    void reorderList(ListNode* head) {        if(head == NULL || head->next == NULL) return;        //slow and fast pointer        ListNode* slow = head;        ListNode* fast = head;        ListNode* pre = NULL;        while(fast != NULL && fast->next != NULL){            pre = slow;            slow = slow->next;            fast = fast->next->next;        }        pre->next = NULL;        ListNode* rhead = reverseList(slow);        ListNode* pcur = head;        ListNode* qcur = rhead;        ListNode* tail = head;        while(qcur != NULL && pcur != NULL){            ListNode * qnext = qcur->next;            qcur->next = pcur->next;            pcur->next = qcur;            pcur = qcur->next;            if(pcur != NULL) tail = pcur;            else tail = qcur;            qcur = qnext;        }        if(qcur != NULL) tail->next = qcur;        return;    }};
0 0
原创粉丝点击