给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4] 输出:[2,1,4,3]
示例 2:
输入:head = [] 输出:[]
示例 3:
输入:head = [1] 输出:[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) {
//定义一个虚拟头结点
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = dummyHead;
while(cur.next != null && cur.next.next != null){
ListNode temp = cur.next;
ListNode temp1 = cur.next.next;
cur.next = temp1;
temp.next = temp1.next;
temp1.next = temp;
cur = temp;
}
return dummyHead.next;
// 代码随想录解法
// // 定义一个虚拟头结点
// ListNode dummyHead = new ListNode(0);
// // 虚拟头结点的下一行结点是头结点
// dummyHead.next = head;
// // 遍历链表
// ListNode cur = dummyHead;
// // cur.next != null 对应着链表长度是偶数,cur是交换后的(循环过后)最后一个结点
// // cur.nexr.next != null,对应着链表长度是奇数,cur是交换后的倒数第二个(循环过后)结点
// //先写cur.next != null而不是先写cur.next.next != null 是因为cur.next ==
// null时cur.next.nxet会报空指针异常
// while (cur.next != null && cur.next.next != null) {
// // 需要存储cur.next 这个临时结点
// ListNode temp = cur.next;
// ListNode temp1 = cur.next.next.next;
// // 改变cur的后继指针指向
// // 此时cur的后继结点是原本链表的cur.next.next
// cur.next = cur.next.next;
// cur.next.next = temp;
// temp.next = temp1;
// cur = cur.next.next;
// }
// return dummyHead.next;
// }
}
}
递归解法:
/**
* 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) {
// 递归解法
// 用 head 表示原始链表的头节点,新的链表的第二个节点,用 newHead 表示新的链表的头节点,原始链表的第二个节点,则原始链表中的其余节点的头节点是
// newHead.next。令 head.next = swapPairs(newHead.next),表示将其余节点进行两两交换,交换后的新的头节点为
// head 的下一个节点。然后令 newHead.next = head,即完成了所有节点的交换。最后返回新的链表的头节点 newHead。
if (head == null || head.next == null) {
return head;
}
ListNode newHead = head.next;
head.next = swapPairs(newHead.next);
newHead.next = head;
return newHead;
}
}