# LeetCode刷题09-链表-24.两两交换链表中的节点

LeetCode刷题09-链表-24.两两交换链表中的节点

题目

给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)

示例1:

输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例2:

输入:head = []
输出:[]

示例3:

输入:head = [1]
输出:[1]

提示:

  • 链表中节点的数目范围是 [0, 100]
  • 0 <= Node.val <= 100

代码

此算法核心在于反转当前节点与前一节点的同时,不能丢失剩余未反转链表入口地址

方式1(双指针法):

该题目难点在模拟链表反转的三个过程,同时体现出添加空头节点对链表操作带来的统一性。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode dummyNode = new ListNode(-1, head);
        ListNode currNode = dummyNode;
        while(currNode.next != null && currNode.next.next != null) {
            ListNode nextNode = currNode.next;
            ListNode next2Node = nextNode.next.next;
            // step 1 
            currNode.next = nextNode.next;
            // step 2
            nextNode.next.next = nextNode;
            // step 3
            nextNode.next = next2Node;
            currNode = currNode.next.next;
        }
        return dummyNode.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值