We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
给你链表的头节点 head 和一个整数 k 。
交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
输入:head = [1,2,3,4,5], k = 2 输出:[1,4,3,2,5]
输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5 输出:[7,9,6,6,8,7,3,0,9,5]
输入:head = [1], k = 1 输出:[1]
输入:head = [1,2], k = 1 输出:[2,1]
输入:head = [1,2,3], k = 2 输出:[1,2,3]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered:
注意审题:是要交换节点值,不需要交换节点。所以可以理解成找到链表的倒数第n个节点,就是使用快慢指针来解决
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func swapNodes(head *ListNode, k int) *ListNode { cur := head quick := head slow := head step := 1 for quick != nil { if step == k { cur = quick } else if step > k { slow = slow.Next } quick = quick.Next step++ } cur.Val, slow.Val = slow.Val, cur.Val return head }
Sorry, something went wrong.
No branches or pull requests
给你链表的头节点 head 和一个整数 k 。
交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
示例 1:
示例 2:
示例 3:
示例 4:
示例 5:
提示:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered: