一.题目:力扣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 指针始终保持在已处理部分的末尾,为下一步的交换做准备。