题目
旋转链表
解析
- 计算确切的旋转点
k = k%len
len - k = newtail
新的头是 len-k + 1 - 斩断这个连接点
伪代码
k = len - k%len
oldh = head
for k != 0 && t = t.next;k--
h = t.next
oldt.next = oldh
代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head == nil {
return head
}
l:=1
oldt := head
for oldt.Next != nil {
oldt = oldt.Next
l++
}
k = l - k%l
if k == l {
return head
}
tail:=head
for k!=1 {
tail=tail.Next
k--
}
oldt.Next = head
head = tail.Next
tail.Next = nil
return head
}
image.png
网友评论