[LeetCode] Swap Nodes in Pairs

本文介绍了一种链表中相邻节点的交换算法实现,通过使用常数空间复杂度完成节点交换,而非修改值。该算法适用于需要改变链表结构但不改变节点值的场景。

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

题目:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

解答:

/**
 * 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) {
        //如果没有节点或只有一个节点
        if(head == NULL || head -> next == NULL) {
            return head;
        }
        else {
            ListNode *first, *second, *newHead = NULL, *pre = NULL;
            first = head;
            //second = head -> next;
            while(first != NULL && first -> next != NULL) {
                second = first -> next;
                
                if(newHead == NULL) {
                    newHead = second;
                }
                
                first -> next = second -> next;
                second -> next = first;
                if(pre != NULL) {
                    pre -> next = second;
                }
                
                pre = first;
                first = first -> next;
            }
            return newHead;
        }
    }
};

思路:

这道题没什么难度,容易忽略的就是只使用两个指针,即指向需要调换的两个元素,这样做是不够的,比如1→2→3→4,第一次调换为2→1→3→4,这时候两个指针应该指向3和4了,但是3、4调换完毕后,1的next仍指向3,导致错误,所以需要第三个指针,指向当前需要调换的两个元素的前一个元素,以便做好next的设置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值