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;
}
}