Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js
2 Star 2 Fork 1

Krum/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.github
.vscode
91
assets
backlog
collections
daily
problems
1.two-sum.en.md
1.two-sum.md
100.same-tree.md
1004.max-consecutive-ones-iii.md
101.symmetric-tree.md
1011.capacity-to-ship-packages-within-d-days-en.md
1011.capacity-to-ship-packages-within-d-days.md
1014.best-sightseeing-pair.md
1015.smallest-integer-divisible-by-k.md
1019.next-greater-node-in-linked-list.md
102.binary-tree-level-order-traversal.md
1020.number-of-enclaves.md
1023.camelcase-matching.md
103.binary-tree-zigzag-level-order-traversal.md
1031.maximum-sum-of-two-non-overlapping-subarrays.md
1032.stream-of-characters.md
104.maximum-depth-of-binary-tree.md
108.convert-sorted-array-to-binary-search-tree.md
109.Convert-Sorted-List-to-Binary-Search-Tree.md
11.container-with-most-water.md
1104.path-in-zigzag-labelled-binary-tree.md
1128.number-of-equivalent-domino-pairs.md
113.path-sum-ii.md
1131.maximum-of-absolute-value-expression.md
1168.optimize-water-distribution-in-a-village-en.md
1168.optimize-water-distribution-in-a-village.md
1186.maximum-subarray-sum-with-one-deletion.md
1203.sort-items-by-groups-respecting-dependencies.md
121.best-time-to-buy-and-sell-stock.md
1218.longest-arithmetic-subsequence-of-given-difference.md
122.best-time-to-buy-and-sell-stock-ii.md
1227.airplane-seat-assignment-probability.md
124.binary-tree-maximum-path-sum.md
125.valid-palindrome.md
1255.maximum-score-words-formed-by-letters.md
1260.shift-2d-grid.md
1261.find-elements-in-a-contaminated-binary-tree.md
1262.greatest-sum-divisible-by-three.md
128.longest-consecutive-sequence.md
129.sum-root-to-leaf-numbers.md
1297.maximum-number-of-occurrences-of-a-substring.md
130.surrounded-regions.md
131.palindrome-partitioning.md
1310.xor-queries-of-a-subarray.md
1332.remove-palindromic-subsequences.md
1334.find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance.md
136.single-number.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.en.md
1371.find-the-longest-substring-containing-vowels-in-even-counts.md
1381.design-a-stack-with-increment-operation.md
139.word-break.md
140.word-break-ii.md
142.Linked-List-Cycle-II.md
1435.jump-game-iv.md
1438.longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md
144.binary-tree-preorder-traversal.md
1449.form-largest-integer-with-digits-that-add-up-to-target.md
145.binary-tree-postorder-traversal.md
146.lru-cache.md
147.insertion-sort-list.md
1494.parallel-courses-ii.md
15.3sum.md
150.evaluate-reverse-polish-notation.md
152.maximum-product-subarray.md
1521.find-a-value-of-a-mysterious-function-closest-to-target.md
1526.minimum-number-of-increments-on-subarrays-to-form-a-target-array.md
155.min-stack.md
1558.minimum-numbers-of-function-calls-to-make-target-array.md
1574.shortest-subarray-to-be-removed-to-make-array-sorted.md
160.Intersection-of-Two-Linked-Lists.md
1631.path-with-minimum-effort.md
1649.create-sorted-array-through-instructions.md
1658.minimum-operations-to-reduce-x-to-zero.md
167.two-sum-ii-input-array-is-sorted.md
1671.minimum-number-of-removals-to-make-mountain-array.md
169.majority-element.md
1697.checking-existence-of-edge-length-limited-paths.md
17.Letter-Combinations-of-a-Phone-Number.md
172.factorial-trailing-zeroes.md
1737.change-minimum-characters-to-satisfy-one-of-three-conditions.md
19.removeNthNodeFromEndofList.md
190.reverse-bits.md
191.number-of-1-bits.md
198.house-robber.en.md
198.house-robber.md
199.binary-tree-right-side-view.md
2.add-two-numbers.en.md
2.add-two-numbers.md
20.valid-parentheses.md
200.number-of-islands.md
201.bitwise-and-of-numbers-range.md
203.remove-linked-list-elements.md
206.reverse-linked-list.md
208.implement-trie-prefix-tree.md
209.minimum-size-subarray-sum.md
21.merge-two-sorted-lists.md
211.add-and-search-word-data-structure-design.md
212.word-search-ii.md
215.kth-largest-element-in-an-array.md
219.contains-duplicate-ii.md
22.generate-parentheses.md
221.maximal-square.md
226.invert-binary-tree.md
227.basic-calculator-ii.md
229.majority-element-ii.md
23.merge-k-sorted-lists.md
230.kth-smallest-element-in-a-bst.md
232.implement-queue-using-stacks.md
236.lowest-common-ancestor-of-a-binary-tree.md
238.product-of-array-except-self.md
239.sliding-window-maximum.md
24.swapNodesInPairs.md
240.search-a-2-d-matrix-ii.md
25.reverse-nodes-in-k-groups-en.md
25.reverse-nodes-in-k-groups.md
26.remove-duplicates-from-sorted-array.md
263.ugly-number.md
279.perfect-squares.md
283.move-zeroes.md
29.divide-two-integers.md
295.find-median-from-data-stream.md
297.serialize-and-deserialize-binary-tree.md
3.longest-substring-without-repeating-characters.md
30.substring-with-concatenation-of-all-words.md
301.remove-invalid-parentheses.md
309.best-time-to-buy-and-sell-stock-with-cooldown.md
31.next-permutation.md
312.burst-balloons.md
32.longest-valid-parentheses.md
322.coin-change.md
328.odd-even-linked-list.md
33.search-in-rotated-sorted-array.md
330.patching-array.md
334.increasing-triplet-subsequence.md
335.self-crossing.md
337.house-robber-iii.md
342.power-of-four.md
343.integer-break.md
349.intersection-of-two-arrays.md
365.water-and-jug-problem.md
371.sum-of-two-integers.md
378.kth-smallest-element-in-a-sorted-matrix.md
380.insert-delete-getrandom-o1.md
39.combination-sum.md
394.decode-string.md
4.median-of-two-sorted-arrays.md
40.combination-sum-ii.md
401.binary-watch.md
416.partition-equal-subset-sum.md
42.trapping-rain-water.en.md
42.trapping-rain-water.md
424.longest-repeating-character-replacement.md
437.path-sum-iii.md
445.add-two-numbers-ii.md
454.4-Sum-ii.en.md
454.4-sum-ii.md
455.AssignCookies.md
46.permutations.md
460.lfu-cache.md
464.can-i-win.md
47.permutations-ii.md
472.concatenated-words.md
474.ones-and-zeros-en.md
48.rotate-image.md
480.sliding-window-median.md
483.smallest-good-base.md
488.zuma-game.md
49.group-anagrams.md
493.reverse-pairs.md
494.target-sum.md
5.longest-palindromic-substring.md
50.pow-x-n.md
501.Find-Mode-in-Binary-Search-Tree-en.md
513.find-bottom-left-tree-value.md
516.longest-palindromic-subsequence.md
518.coin-change-2.md
52.N-Queens-II.md
53.maximum-sum-subarray-cn.md
53.maximum-sum-subarray-en.md
547.friend-circles-en.md
547.friend-circles.md
55.jump-game.md
56.merge-intervals.md
560.subarray-sum-equals-k.en.md
560.subarray-sum-equals-k.md
5640.maximum-xor-with-an-element-from-array.md
57.insert-interval.md
575.distribute-candies.md
60.permutation-sequence.md
609.find-duplicate-file-in-system.md
61.Rotate-List.md
611.valid-triangle-number.md
62.unique-paths.md
63.unique-paths-ii.md
66.plus-one.md
665.non-decreasing-array.md
673.number-of-longest-increasing-subsequence.md
679.24-game.md
686.repeated-string-match.md
715.range-module.md
718.maximum-length-of-repeated-subarray.md
721.accounts-merge.md
73.set-matrix-zeroes.md
75.sort-colors.md
754.reach-a-number.md
768.max-chunks-to-make-sorted-ii.md
78.subsets-en.md
78.subsets.md
785.is-graph-bipartite.md
79.word-search-en.md
79.word-search.md
790.domino-and-tromino-tiling.md
799.champagne-tower.md
80.remove-duplicates-from-sorted-array-ii.md
801.minimum-swaps-to-make-sequences-increasing.md
805.split-array-with-same-average.md
816.ambiguous-coordinates.md
820.short-encoding-of-words.md
821.shortest-distance-to-a-character.md
839.similar-string-groups.md
84.largest-rectangle-in-histogram.md
85.maximal-rectangle.md
86.partition-list.md
874.walking-robot-simulation.md
875.koko-eating-bananas.md
877.stone-game.md
88.merge-sorted-array.md
886.possible-bipartition.md
887.super-egg-drop.md
895.maximum-frequency-stack.md
898.bitwise-ors-of-subarrays.md
90.subsets-ii-en.md
90.subsets-ii.md
900.rle-iterator.md
91.decode-ways.md
911.online-election.md
912.sort-an-array.md
92.reverse-linked-list-ii.md
932.beautiful-array.md
935.knight-dialer.md
94.binary-tree-inorder-traversal.md
947.most-stones-removed-with-same-row-or-column.md
95.unique-binary-search-trees-ii.md
959.regions-cut-by-slashes.md
96.unique-binary-search-trees.md
975.odd-even-jump.md
978.longest-turbulent-subarray.md
98.validate-binary-search-tree.md
987.vertical-order-traversal-of-a-binary-tree.md
995.minimum-number-of-k-consecutive-bit-flips.md
Number-Stream-to-Intervals.md
binode-lcci.md
get-kth-magic-number-lcci.md
lcp20.meChtZ.md
max-black-square-lcci.md
selected
templates
thinkings
todo/candidates
.gitignore
CONTRIBUTING.en.md
CONTRIBUTING.md
Kapture 2020-08-19 at 11.37.36.gif
LICENSE.txt
README.en.md
README.md
SUMMARY.md
book.json
cover.jpg
donation.md
epilogue.md
introduction.md
package.json
thanksGiving.md
thanksGiving2.md
thanksGiving3.md
克隆/下载
24.swapNodesInPairs.md 4.53 KB
一键复制 编辑 原始数据 按行查看 历史
lucifer 提交于 4年前 . fix: $$ -> $

题目地址(24. 两两交换链表中的节点)

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

题目描述

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

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

image.png

示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]

示例 2:
输入:head = []
输出:[]

示例 3:
输入:head = [1]
输出:[1]

提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100

前置知识

  • 链表

公司

  • 阿里
  • 腾讯
  • 百度
  • 字节

思路

设置一个 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

(图片来自: https://github.com/MisterBooo/LeetCodeAnimation)

关键点解析

  1. 链表这种数据结构的特点和使用

  2. dummyHead 简化操作

代码

  • 语言支持:JS,Python3, Go, PHP, CPP

JS Code:

/**
 * 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;
};

Python Code:

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

Go Code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	if head == nil || head.Next == nil {
		return head
	}

	next := head.Next
	head.Next = swapPairs(next.Next) // 剩下的节点递归已经处理好, 拼接到前 2 个节点上
	next.Next = head
	return next
}

PHP Code:

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val = 0, $next = null) {
 *         $this->val = $val;
 *         $this->next = $next;
 *     }
 * }
 */
class Solution
{

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function swapPairs($head)
    {
        if (!$head || !$head->next) return $head;

        /** @var ListNode $next */
        $next = $head->next;
        $head->next = (new Solution())->swapPairs($next->next); // 递归已经将后面链表处理好, 拼接到前面的元素上
        $next->next = $head;
        return $next;
    }
}

CPP Code:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode h, *tail = &h;
        while (head && head->next) {
            auto p = head, q = head->next;
            head = q->next;
            q->next = p;
            tail->next = q;
            tail = p;
        }
        tail->next = head;
        return h.next;
    }
};

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(1)

大家对此有何看法,欢迎给我留言,我有时间都会一一查看回答。更多算法套路可以访问我的 LeetCode 题解仓库:https://github.com/azl397985856/leetcode 。 目前已经 37K star 啦。 大家也可以关注我的公众号《力扣加加》带你啃下算法这块硬骨头。

Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/Krum/leetcode.git
git@gitee.com:Krum/leetcode.git
Krum
leetcode
leetcode
master

搜索帮助