题目描述
原题链接
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
成绩
解题思路
虚拟节点+遍历链表
代码实现
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummyHead = new ListNode(); // 创建虚拟节点
dummyHead.next = head;
ListNode temp = dummyHead;
ListNode frontIndex;
ListNode backendIndex;
// temp.next 为 null 时,表示没有多的节点了
// temp.next.next 为 null 时,表示只剩下一个节点了,无需进行交换操作
while (temp.next != null && temp.next.next != null) {
frontIndex = temp.next;
backendIndex = temp.next.next;
temp.next = backendIndex;
frontIndex.next = backendIndex.next;
backendIndex.next = frontIndex;
temp = temp.next.next;
}
return dummyHead.next;
}
}