这是链表的第8篇算法,力扣链接。
给你一个链表的头节点
head
,旋转链表,将链表每个节点向右移动k
个位置。示例 1:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]示例 2:
输入:head = [0,1,2], k = 4 输出:[2,0,1]
这里先采用快慢指针试一下:
func rotateRight(head *ListNode, k int) *ListNode {if head == nil || head.Next == nil || k == 0 {return head}result := &ListNode{Next: head}left, right := head, headfor i := 0; i < k; i++ {if right.Next == nil {right = head} else {right = right.Next}}for right.Next != nil {left = left.Nextright = right.Next}if left.Next == nil {return result.Next}result.Next = left.Nextright.Next = headleft.Next = nilreturn result.Next
}
还有另一个方法,就是计数法,浅试一下。
func rotateRight(head *ListNode, k int) *ListNode {if head == nil || head.Next == nil || k == 0 {return head}cur := headcount := 1for cur.Next != nil {count++cur = cur.Next}pos := count - k%countif count == 0 {return head}// 成环cur.Next = headfor pos > 0 {cur = cur.Nextpos--}// 最后一次取下一个值 将指针移到指定位置result := cur.Next// 破环cur.Next = nilreturn result
}