|
| 1 | +# [Swap Nodes in Pairs][title] |
| 2 | + |
| 3 | +## Description |
| 4 | + |
| 5 | +Given a linked list, swap every two adjacent nodes and return its head. |
| 6 | + |
| 7 | +For example, |
| 8 | +Given `1->2->3->4`, you should return the list as `2->1->4->3`. |
| 9 | + |
| 10 | +Your algorithm should use only constant space. You may **not** modify the values in the list, only nodes itself can be changed. |
| 11 | + |
| 12 | +**Tags:** Linked List |
| 13 | + |
| 14 | + |
| 15 | +## 思路 0 |
| 16 | + |
| 17 | +题意是让你交换链表中相邻的两个节点,最终返回交换后链表的头,限定你空间复杂度为 O(1)。我们可以用递归来算出子集合的结果,递归的终点就是指针指到链表末少于两个元素时,如果不是终点,那么我们就对其两节点进行交换,这里我们需要一个临时节点来作为交换桥梁,就不多说了。 |
| 18 | + |
| 19 | +```java |
| 20 | +/** |
| 21 | + * Definition for singly-linked list. |
| 22 | + * public class ListNode { |
| 23 | + * int val; |
| 24 | + * ListNode next; |
| 25 | + * ListNode(int x) { val = x; } |
| 26 | + * } |
| 27 | + */ |
| 28 | +class Solution { |
| 29 | + public ListNode swapPairs(ListNode head) { |
| 30 | + if (head == null || head.next == null) return head; |
| 31 | + ListNode node = head.next; |
| 32 | + head.next = swapPairs(node.next); |
| 33 | + node.next = head; |
| 34 | + return node; |
| 35 | + } |
| 36 | +} |
| 37 | +``` |
| 38 | + |
| 39 | + |
| 40 | +## 思路 1 |
| 41 | + |
| 42 | +另一种实现方式就是用循环来实现了,两两交换节点,也需要一个临时节点来作为交换桥梁,直到当前指针指到链表末少于两个元素时停止,代码很简单,如下所示。 |
| 43 | + |
| 44 | +```java |
| 45 | +/** |
| 46 | + * Definition for singly-linked list. |
| 47 | + * public class ListNode { |
| 48 | + * int val; |
| 49 | + * ListNode next; |
| 50 | + * ListNode(int x) { val = x; } |
| 51 | + * } |
| 52 | + */ |
| 53 | +class Solution { |
| 54 | + public ListNode swapPairs(ListNode head) { |
| 55 | + ListNode preHead = new ListNode(0), cur = preHead; |
| 56 | + preHead.next = head; |
| 57 | + while (cur.next != null && cur.next.next != null) { |
| 58 | + ListNode temp = cur.next.next; |
| 59 | + cur.next.next = temp.next; |
| 60 | + temp.next = cur.next; |
| 61 | + cur.next = temp; |
| 62 | + cur = cur.next.next; |
| 63 | + } |
| 64 | + return preHead.next; |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | + |
| 70 | +## 结语 |
| 71 | + |
| 72 | +如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-java-leetcode][ajl] |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +[title]: https://leetcode.com/problems/swap-nodes-in-pairs |
| 77 | +[ajl]: https://github.com/Blankj/awesome-java-leetcode |
0 commit comments