【亡羊补牢】挑战数据结构与算法 第58期 LeetCode 24. 两两交换链表中的节点(链表)
发布日期:2021-06-29 14:34:37 浏览次数:2 分类:技术文章

本文共 1364 字,大约阅读时间需要 4 分钟。

仰望星空的人,不应该被嘲笑

题目描述

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

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

示例:

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

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

非递归解法

/** * Definition for singly-linked list. * function ListNode(val) { *     this.val = val; *     this.next = null; * } *//** * @param {ListNode} head * @return {ListNode} */var swapPairs = function(head) {
if(head == null || head.next == null) return head; let hummyHead = new ListNode(); // 虚拟节点 hummyHead.next = head; let p = hummyHead; let node1,node2; // 当前要交换的两个节点 while((node1 = p.next) && (node2 = p.next.next)){
// 进行交换操作 node1.next = node2.next; node2.next = node1; // 将链表串起来 p.next = node2; p = node1; } return hummyHead.next;};

递归解法

/** * Definition for singly-linked list. * function ListNode(val) { *     this.val = val; *     this.next = null; * } *//** * @param {ListNode} head * @return {ListNode} */var swapPairs = function (head) {
if (!head || !head.next) return head; let node1 = head, node2 = head.next; node1.next = swapPairs(node2.next); node2.next = node1; return node2;};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!

,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退

转载地址:https://chocolate.blog.csdn.net/article/details/108918987 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【亡羊补牢】挑战数据结构与算法 第59期 LeetCode 19. 删除链表的倒数第N个节点(链表)
下一篇:【亡羊补牢】挑战数据结构与算法 第57期 LeetCode 203. 移除链表元素(链表)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月06日 11时56分51秒