算法 链表 24. 两两交换链表中的节点


一.题目:力扣24题

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

二. java代码

public class SwapPairs {
    public static void main(String[] args) {
        // 创建链表 1->2->3->4
        ListNodeSwapPairs head = new ListNodeSwapPairs(1);
        head.next = new ListNodeSwapPairs(2);
        head.next.next = new ListNodeSwapPairs(3);
        head.next.next.next = new ListNodeSwapPairs(4);

        System.out.println("原始链表:");
        printList(head);

        SolutionSwapPairs solution = new SolutionSwapPairs();
        ListNodeSwapPairs swappedHead = solution.swapPairs(head);

        System.out.println("交换后的链表:");
        printList(swappedHead);
    }

    // 辅助方法,用于打印链表
    public static void printList(ListNodeSwapPairs node) {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println(); // 确保在打印完列表后有换行
    }
}
class ListNodeSwapPairs{
    int val;
    ListNodeSwapPairs next;

    public ListNodeSwapPairs(int val){
        this.val=val;
        this.next=null;
    }
}

class SolutionSwapPairs{
    public ListNodeSwapPairs swapPairs(ListNodeSwapPairs head){
        ListNodeSwapPairs dummyhead =new ListNodeSwapPairs(-1);
        dummyhead.next=head;
        ListNodeSwapPairs cur=dummyhead;
        ListNodeSwapPairs temp;
        ListNodeSwapPairs firstnode;
        ListNodeSwapPairs secondnode;
        while (cur.next!=null && cur.next.next!=null){
            temp=cur.next.next.next;
            firstnode=cur.next;
            secondnode=cur.next.next;
            cur.next=secondnode;
            secondnode.next=firstnode;
            firstnode.next=temp;
            cur=firstnode;
        }
        return dummyhead.next;
    }
}

三.交换过程

设初始链表是这样的结构:

[1] -> [2] -> [3] -> [4]

我们希望交换每两个相邻的节点,即希望得到:

[2] -> [1] -> [4] -> [3]

假设我们用 cur 来表示当前操作的节点(在代码中是 cur 指针),初始化时指向一个虚拟头节点(Dummy Node),这个虚拟头节点的 next 指向链表的实际头节点 [1]。

初始状态:

Dummy -> [1] -> [2] -> [3] -> [4]
  ↑
 cur

第一对交换 [1] 和 [2]:
temp 指向 [3]
firstnode 指向 [1]
secondnode 指向 [2]
执行交换后:

Dummy -> [2] -> [1] -> [3] -> [4]
              ↑
             cur

此时,cur(firstnode)已经更新到 [1] 上,准备下一轮交换。

第二对交换 [3] 和 [4]:
由于 cur 已经移动到了 [1],接下来检查的是 [3] 和 [4]:

Dummy -> [2] -> [1] -> [3] -> [4]
                          ↑
                         cur

temp 指向 null(因为 [4] 后面没有节点了)
firstnode 指向 [3]
secondnode 指向 [4]
执行交换后:

Dummy -> [2] -> [1] -> [4] -> [3]
                              ↑
                             cur

在每次交换后,cur 指针都会更新到当前交换对的后一个节点上,也就是说,cur 指针始终保持在已处理部分的末尾,为下一步的交换做准备。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值