leecode/problems/24.swapNodesInPairs.md
2020-05-22 18:17:19 +08:00

95 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
https://leetcode.com/problems/swap-nodes-in-pairs/description/
## 题目描述
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
## 思路
设置一个 dummy 节点简化操作dummy next 指向 head。
1. 初始化 first 为第一个节点
2. 初始化 second 为第二个节点
3. 初始化 current 为 dummy
4. first.next = second.next
5. second.next = first
6. current.next = second
7. current 移动两格
8. 重复
![24.swap-nodes-in-pairs](../assets/24.swap-nodes-in-pairs.gif)
(图片来自: https://github.com/MisterBooo/LeetCodeAnimation)
## 关键点解析
1. 链表这种数据结构的特点和使用
2. dummyHead 简化操作
## 代码
* 语言支持JSPython3
```js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
const dummy = new ListNode(0);
dummy.next = head;
let current = dummy;
while (current.next != null && current.next.next != null) {
// 初始化双指针
const first = current.next;
const second = current.next.next;
// 更新双指针和 current 指针
first.next = second.next;
second.next = first;
current.next = second;
// 更新指针
current = current.next.next;
}
return dummy.next;
};
```
Python3 Code:
```python
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
"""
用递归实现链表相邻互换:
第一个节点的 next 是第三、第四个节点交换的结果,第二个节点的 next 是第一个节点;
第三个节点的 next 是第五、第六个节点交换的结果,第四个节点的 next 是第三个节点;
以此类推
:param ListNode head
:return ListNode
"""
# 如果为 None 或 next 为 None则直接返回
if not head or not head.next:
return head
_next = head.next
head.next = self.swapPairs(_next.next)
_next.next = head
return _next
```