这是链表的第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, head
for i := 0; i < k; i++ {
if right.Next == nil {
right = head
} else {
right = right.Next
}
}
for right.Next != nil {
left = left.Next
right = right.Next
}
if left.Next == nil {
return result.Next
}
result.Next = left.Next
right.Next = head
left.Next = nil
return result.Next
}
还有另一个方法,就是计数法,浅试一下。
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil || k == 0 {
return head
}
cur := head
count := 1
for cur.Next != nil {
count++
cur = cur.Next
}
pos := count - k%count
if count == 0 {
return head
}
// 成环
cur.Next = head
for pos > 0 {
cur = cur.Next
pos--
}
// 最后一次取下一个值 将指针移到指定位置
result := cur.Next
// 破环
cur.Next = nil
return result
}