1. 题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
Related Topics 递归 链表
👍 946 👎 0
2. 题解
2.1 解法1: 非递归的双指针
每次交换前指向交换前的一个结点
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null) return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode p=dummy;
while(true){
if(p.next==null || p.next.next==null) break;
ListNode one=p.next, two=p.next.next, three=p.next.next.next;
p.next=two;
two.next=one;
one.next=three;
p=p.next.next;
}
return dummy.next;
}
}
写法2
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode start = cur.next, end = cur.next.next, next = cur.next.next.next;
cur.next = end;
end.next = start;
start.next = next;
cur = start;
}
return dummy.next;
}
}
2.2 解法2: 递归法
递归函数
作用: 交换以head 为头结点的链表
返回值: 交换后链表的头结点
终止条件: head== null 或 head.next== null
调用过程: 每次交换 head 和 head.next 结点, head.next 结点后的子链表递归调用函数返回已经交换完成的头结点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
// 先交换 head与 head.next 结点, 再连接后面递归处理的子链表
ListNode next = head.next.next;
ListNode newHead = head.next;
newHead.next = head;
head.next = swapPairs(next);
return newHead;
}
}