LeetCode 143. 重排链表

难度:中等。
标签:栈,递归,链表,双指针。

先使用快慢指针找到链表的分界点处,将分界点及以后的链表反转。
然后将两个链表合并起来。
注意第52行,需要将前面的链表尾节点指向nullptr,否则他之前指向的是后面链表的第一个节点,该节点已经被反转到后面链表的最后一个了。如果不加上这句,会报以下错:
AddressSanitizer: heap-use-after-free
在这里插入图片描述

正确解法:

/**
 * 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;
        ListNode* node1 = head;
        ListNode* slow = head->next, *fast = head->next;
        while(fast != nullptr && fast->next != nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* node2 = nullptr, *temp = nullptr;
        while(slow != nullptr){
            if(slow->next == nullptr){
                slow->next = temp;
                node2 = slow;
                break;
            }
            else if(slow->next->next == nullptr){
                node2 = slow->next;
                slow->next->next = slow;
                slow->next = temp;
                break;
            }
            ListNode* next_node = slow->next;
            ListNode* next_next_node = next_node->next;
            next_node->next = slow;
            slow->next = temp;
            slow = next_next_node;
            temp = next_node;
        }
        
        int i = 0;
        while(node1 != nullptr && node2 != nullptr){
            if(i % 2 == 0){
                ListNode* next1 = node1->next;
                node1->next = node2;
                node1 = next1;
            }
            else{
                ListNode* next2 = node2->next;
                node2->next = node1;
                if(next2 == nullptr)node1->next = nullptr;
                node2 = next2;
            }
            i++;
        }

    }
};

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值