|
| 1 | +## 题目地址 |
| 2 | +https://leetcode.com/problems/swap-nodes-in-pairs/description/ |
| 3 | + |
| 4 | +## 题目描述 |
| 5 | +Given a linked list, swap every two adjacent nodes and return its head. |
| 6 | + |
| 7 | +You may not modify the values in the list's nodes, only nodes itself may be changed. |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +Example: |
| 12 | + |
| 13 | +Given 1->2->3->4, you should return the list as 2->1->4->3. |
| 14 | +## 思路 |
| 15 | + |
| 16 | +设置一个dummy 节点简化操作。 |
| 17 | + |
| 18 | +设置一个虚拟头结点dummyHead |
| 19 | + |
| 20 | +设置需要交换的两个节点分别为node1、node2,同时设置node2的下一个节点next |
| 21 | + |
| 22 | +在这一轮操作中 |
| 23 | +将node2节点的next设置为node1节点 |
| 24 | + |
| 25 | +将node1节点的next设置为next节点 |
| 26 | + |
| 27 | +将dummyHead节点的next设置为node2 |
| 28 | + |
| 29 | +结束本轮操作 |
| 30 | + |
| 31 | +接下来的每轮操作都按照上述进行。 |
| 32 | + |
| 33 | + |
| 34 | + |
| 35 | +(图片来自: https://github.com/MisterBooo/LeetCodeAnimation) |
| 36 | + |
| 37 | +## 关键点解析 |
| 38 | + |
| 39 | +1. 链表这种数据结构的特点和使用 |
| 40 | + |
| 41 | +2. dummyHead简化操作 |
| 42 | + |
| 43 | +## 代码 |
| 44 | +```js |
| 45 | +/* |
| 46 | + * @lc app=leetcode id=24 lang=javascript |
| 47 | + * |
| 48 | + * [24] Swap Nodes in Pairs |
| 49 | + * |
| 50 | + * https://leetcode.com/problems/swap-nodes-in-pairs/description/ |
| 51 | + * |
| 52 | + * algorithms |
| 53 | + * Medium (43.33%) |
| 54 | + * Total Accepted: 287.2K |
| 55 | + * Total Submissions: 661.3K |
| 56 | + * Testcase Example: '[1,2,3,4]' |
| 57 | + * |
| 58 | + * Given a linked list, swap every two adjacent nodes and return its head. |
| 59 | + * |
| 60 | + * You may not modify the values in the list's nodes, only nodes itself may be |
| 61 | + * changed. |
| 62 | + * |
| 63 | + * |
| 64 | + * |
| 65 | + * Example: |
| 66 | + * |
| 67 | + * |
| 68 | + * Given 1->2->3->4, you should return the list as 2->1->4->3. |
| 69 | + * |
| 70 | + */ |
| 71 | +/** |
| 72 | + * Definition for singly-linked list. |
| 73 | + * function ListNode(val) { |
| 74 | + * this.val = val; |
| 75 | + * this.next = null; |
| 76 | + * } |
| 77 | + */ |
| 78 | +/** |
| 79 | + * @param {ListNode} head |
| 80 | + * @return {ListNode} |
| 81 | + */ |
| 82 | +var swapPairs = function(head) { |
| 83 | + const dummy = new ListNode(0); |
| 84 | + dummy.next = head; |
| 85 | + let current = dummy; |
| 86 | + while (current.next != null && current.next.next != null) { |
| 87 | + const first = current.next; |
| 88 | + const second = current.next.next; |
| 89 | + first.next = second.next; |
| 90 | + current.next = second; |
| 91 | + current.next.next = first; |
| 92 | + current = current.next.next; |
| 93 | + } |
| 94 | + return dummy.next; |
| 95 | +}; |
| 96 | + |
| 97 | +``` |
0 commit comments