力扣143 重排链表 快慢指针 指针反转 指针插入

注意点1:

快慢指针求中间节点,向下取的!!!!

所以我们在循环的时候是需要fast->next  fast->next->next

 

注意点2:

链表反转的时候要返回头节点

此时cur是nullptr 需要返回的是pre

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(!head)return;
        ListNode* mid = findmid(head);
        ListNode* l1 = head;
        ListNode* l2 = mid->next;
        mid->next = nullptr;
        l2 = overload(l2);
        ansnode(l1,l2);
    }
    ListNode* findmid(ListNode* head)
    {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next != nullptr && fast->next->next != nullptr)
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
    ListNode* overload(ListNode* head)
    {
        ListNode* cur = head;
        ListNode* pre = nullptr;
        while(cur)
        {
            ListNode* tmpnode = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmpnode;
        }
        return pre;//pre
    }
    void ansnode(ListNode*l1,ListNode* l2)
    {
        ListNode* l1next;
        ListNode* l2next;

        while(l1 != nullptr && l2 != nullptr)
        {
            l1next = l1->next;
            l2next = l2->next;

            l1->next = l2;
            l1 = l1next;

            l2->next = l1;
            l2 = l2next;
        }
    }
};

2、除了上面方法还可以直接stl 容器

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if(head == nullptr)return;
        vector<ListNode*>vec;
        ListNode* p = head;

        int j = 0;
        int i = 0;
        while(p)
        {
            vec.push_back(p);
            j++;
            p = p->next;
        }
        j--;
        while(i < j)
        {
            vec[i]->next = vec[j];
            vec[j--]->next = vec[++i];
        }
        vec[i]->next = nullptr;
    }
};

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值