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


题目分析:

1、边界情况:链表为空或者链表长度为1时,都可以不用做操作。

2、拆分最终的链表,发现前半段L0, L1, L2,...顺序没有变化;后半段Ln, Ln-1,Ln-2,...顺序颠倒。


思路:

1、找出中间节点,将链表分为前后两段。(可以找中间节点的前一个节点,因为要将该节点的next指向null,只不过翻转时向后在移动一个就好了)

2、将后半段链表翻转

3.、设一个新节点的next指向于head,从而在每次循环中都是先操作前半段,在操作后半段

4、注意控制好循环条件,链表总长度可能为奇数或者是偶数


代码:

/**
 * 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* p = new ListNode(0);
        p->next = head;
        ListNode* p1 = head;
        ListNode* middle = getPreMiddle(head); //中间节点的前一个节点
        ListNode* p2 = reverseList(middle->next); // 先翻转后半段,在将middle指向null
        middle->next = nullptr;
        while (p1 != nullptr)        //链表总长度为偶数时,直接结束循环
        {
            p->next = p1;
            p1 = p1->next;
            p = p->next;
            if (p2 != nullptr)       //链表总长度为奇数时,多指向一次前半段最后一个节点
            {
                p->next = p2;
                p2 = p2->next;
                p = p->next;
            }
            else
                break;
        }
    }
    
    ListNode* getPreMiddle(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr)   return head;
        ListNode* pfast = head;
        ListNode* pslow = head;
        while (pfast->next != nullptr && pfast->next->next != nullptr)
        {
            pfast = pfast->next->next;
            pslow = pslow->next;
        }
        return pslow;
    }

    ListNode* reverseList(ListNode* head)
    {
        if (head == nullptr || head->next == nullptr)   return head;
        if (head->next->next == nullptr)    
        {
            ListNode* p = head->next;
            head->next = nullptr;
            p->next = head;
            return p;
        }
        ListNode* pre = head;
        ListNode* now = head->next;
        ListNode* next = now->next;
        pre->next = nullptr;
        while (next != nullptr)
        {
            now->next = pre;
            pre = now;
            now = next;
            next = next->next;
        }
        now->next = pre;
        return now;
    }
};

备注:第一次做medium级别的题,还是很开心的。自己判断循环条件的能力太弱,要多加练习。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值