[数据结构]两两交换链表中的节点(leetcode24)c++

本文详细介绍了如何使用C++解决LeetCode上的第24题——两两交换链表中的节点。通过遍历链表,标记待交换节点,并更新链表指针,实现链表中相邻节点的两两交换。代码简洁,易于理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两两交换链表中的节点(leetcode24)c++

在这里插入图片描述

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

    //1.分别遍历偶数节点和奇数节点
    //2.交换两个节点
    //3.更新pre,指向交换后的头
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        //1.分别遍历偶数节点和奇数节点
        //2.交换两个节点
        //3.更新pre,指向交换后的头

        //--[1]--
        ListNode *new_head=new ListNode(0);
        new_head->next=head;
        ListNode *pre=new_head;
        //~

        //--[2]--
        while(head && head->next){
            //标记两个待交换结点
            ListNode *first=head;
            ListNode *second=head->next;

            //swap
            pre->next=second;
            first->next=first->next->next;
            second->next=first;

            //更新pre
            pre=first;
            head=first->next;//后移
        }
        //~

        //--[3]--
        return new_head->next;
        //~
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值