标签:img var ret func int com val UNC load
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func rotateRight(head *ListNode, k int) *ListNode {
if head==nil || head.Next==nil || k==0{
return head
}
var length = 1//链表总长度
var curr = head
for curr.Next!=nil{
length++
curr = curr.Next
}
// 刚好旋转回去
k = k%length
if k == 0{
return head
}
// 首先首尾相连成环,找到倒数第k+1个节点,成为新的头节点
curr.Next = head
for i:=0;i<length-k;i++{
curr = curr.Next
}
// curr此时指向新的尾节点
newHead := curr.Next//新的尾节点的下一个节点即为新的头节点
curr.Next = nil//断尾
return newHead
}
标签:img var ret func int com val UNC load
原文地址:https://www.cnblogs.com/pangqianjin/p/14641074.html