LeetCode24-两两交换链表中的节点

题目链接

英文链接:https://leetcode.com/problems/swap-nodes-in-pairs/

中文链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

题目详述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

1
给定 1->2->3->4, 你应该返回 2->1->4->3.

题目详解

画个示意图,正确地更改指针指向即可。

迭代版。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class LeetCode_00024 {

// 迭代
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode first = cur.next;
ListNode second = cur.next.next;
first.next = second.next;
second.next = first;
cur.next = second;
cur = cur.next.next;
}
return dummy.next;
}
}

递归版。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00024 {

// 递归
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = head;
head = head.next;
p.next = head.next;
head.next = p;
p.next = swapPairs(p.next);
return head;
}
}