交换相邻节点
1
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class SwapNodes {
// 方法:交换相邻节点
public static ListNode swapPairs(ListNode head) {
// 如果链表为空或只有一个节点,则直接返回
if (head == null || head.next == null) {
return head;
}
// 创建一个虚拟节点作为新的头节点的前驱
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
// 迭代交换相邻节点
while (current.next != null && current.next.next != null) {
// 初始化要交换的两个节点
ListNode first = current.next;
ListNode second = current.next.next;
// 交换节点
first.next = second.next;
second.next = first;
current.next = second;
// 移动指针到下一个要交换的节点位置
current = first;
}
// 返回新的头节点
return dummy.next;
}
// 辅助方法:打印链表
public static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
// 创建链表 1 -> 2 -> 3 -> 4
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
System.out.println("原始链表:");
printList(head);
// 交换相邻节点
head = swapPairs(head);
System.out.println("交换相邻节点后的链表:");
printList(head);
}
}