We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这题本意比较简单,1 -> 2 -> 3 -> 4 的情况下可以定义一个递归的辅助函数 helper,这个辅助函数对于节点和它的下一个节点进行交换,比如 helper(1) 处理 1 -> 2,并且把交换变成 2 -> 1 的尾节点 1的next继续指向 helper(3)也就是交换后的 4 -> 3。
1 -> 2 -> 3 -> 4
helper
helper(1)
1 -> 2
2 -> 1
1
next
helper(3)
4 -> 3
边界情况在于,如果顺利的作了两两交换,那么交换后我们的函数返回出去的是 交换后的头部节点,但是如果是奇数剩余项的情况下,没办法做交换,那就需要直接返回 原本的头部节点。这个在 helper函数和主函数中都有体现。
let swapPairs = function (head) { if (!head) return null let helper = function (node) { let tempNext = node.next if (tempNext) { let tempNextNext = node.next.next node.next.next = node if (tempNextNext) { node.next = helper(tempNextNext) } else { node.next = null } } return tempNext || node } let res = helper(head) return res || head }
The text was updated successfully, but these errors were encountered:
function swapPairs(head: ListNode | null): ListNode | null { if (head === null || head.next === null) { return head; } let nextNode = head.next; head.next = swapPairs(nextNode.next); nextNode.next = head; return nextNode; };
这是我从评论里看到的最简洁的解法
Sorry, something went wrong.
No branches or pull requests
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
这题本意比较简单,
1 -> 2 -> 3 -> 4
的情况下可以定义一个递归的辅助函数helper
,这个辅助函数对于节点和它的下一个节点进行交换,比如helper(1)
处理1 -> 2
,并且把交换变成2 -> 1
的尾节点1
的next
继续指向helper(3)
也就是交换后的4 -> 3
。边界情况在于,如果顺利的作了两两交换,那么交换后我们的函数返回出去的是 交换后的头部节点,但是如果是奇数剩余项的情况下,没办法做交换,那就需要直接返回 原本的头部节点。这个在
helper
函数和主函数中都有体现。The text was updated successfully, but these errors were encountered: