代码随想录第四天 | 交换链表 + 删除倒数第n个节点 + 环形链表

Leetcode24 两两交换链表

链接: https://leetcode.cn/problems/swap-nodes-in-pairs/description/

思路: 明确交换规律. 由于中间节点交换时需要插入到两个节点中间, 所以为了保持统一, 引入一个虚拟的头结点. 那么交换规律为:
0 -> 1 -> 2 -> 3 -> 4
^ ^ ^
last cur next
1->3: cur->next = next->next;
2->1: next->next = cur;
0->2: last->next = next
此时的交换结果为:
0 -> 2 -> 1 -> 3 -> 4
^ ^ ^
last next cur
在下次循环前, 需更新索引
last = cur;
cur = cur->next;

ListNode* swapPairs(ListNode* head) {
    if (head == nullptr || head->next == nullptr) {
        return head;
    }

    ListNode* dummy_head = new ListNode(0);
    dummy_head->next = head;
    ListNode* current_node = head;
    ListNode* last_node = dummy_head;
    while (current_node!= nullptr && current_node->next != nullptr) {
        ListNode* next_node = current_node->next;
        current_node->next = current_node->next->next;
        next_node->next = current_node;
        last_node->next = next_node;
        // 更新索引
        last_node = current_node;
        current_node = current_node->next;
    }
    return dummy_head->next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值