Skip to content
New issue

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

1721. 交换链表中的节点 #92

Open
yankewei opened this issue Jan 12, 2021 · 1 comment
Open

1721. 交换链表中的节点 #92

yankewei opened this issue Jan 12, 2021 · 1 comment
Labels
中等 题目难度为中等 双指针 题目包含双指针解法 链表 题目类型为链表

Comments

@yankewei
Copy link
Owner

给你链表的头节点 head 和一个整数 k 。

交换 链表正数第 k 个节点和倒数第 k 个节点的后,返回链表的头节点(链表 从 1 开始索引)。

示例 1:

示例

输入:head = [1,2,3,4,5], k = 2
输出:[1,4,3,2,5]

示例 2:

输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
输出:[7,9,6,6,8,7,3,0,9,5]

示例 3:

输入:head = [1], k = 1
输出:[1]

示例 4:

输入:head = [1,2], k = 1
输出:[2,1]

示例 5:

输入:head = [1,2,3], k = 2
输出:[1,2,3]

提示:

  • 链表中节点的数目是 n
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 中等 题目难度为中等 双指针 题目包含双指针解法 链表 题目类型为链表 labels Jan 12, 2021
@yankewei
Copy link
Owner Author

快慢指针

注意审题:是要交换节点值,不需要交换节点。所以可以理解成找到链表的倒数第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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 双指针 题目包含双指针解法 链表 题目类型为链表
Projects
None yet
Development

No branches or pull requests

1 participant