[leetcode] 143. Reorder List 解题报告

题目链接:https://leetcode.com/problems/reorder-list/

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

思路:可以将链表从中间分割成两段,然后后半段就地逆置之后合并插入两个链表即可,代码比较长,不过效率还是不错的,时间复杂度O(n)。

代码如下:

/**
 * 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 || !head->next) return;
        ListNode* p = head, *q;
        int n = 0, i =1;
        while(p)
        {
            n++;
            p = p->next;
        }
        p = head;
        while(i < (n+1)/2)//找到分割点
        {
            i++;
            p = p->next;
        }
        ListNode *pHead = p->next;
        p->next = NULL;
        ListNode *vHead = new ListNode(0);
        vHead->next = pHead;
        q = pHead->next;
        pHead->next = NULL;
        while(q)//reverse
        {
            p = q->next;
            q->next = vHead->next;
            vHead->next = q;
            q = p;
        }
        p = vHead->next;
        q = head;
        while(p)//合并两个链表
        {
            ListNode *tem = p->next;
            p->next = q->next;
            q->next = p;
            q = q->next->next;
            p = tem;
        }
    }
};


你可能感兴趣的:(LeetCode,链表)