61. 旋转链表

获取到链表的总长度值
示例2中如果k=3的话 实际上整个链表并不需要移动
示例2中k=4 只是把链表最后一个移到头部
示例1k=2 是把尾部两个元素移到头部
移动的索引位置=链表长度-(k%链表长度)
package mainimport "fmt"type ListNode struct {Val intNext *ListNode}func rotateRight(head *ListNode, k int) *ListNode {if head==nil||head.Next==nil||k==0 {return head}count :=1cursor := headfor cursor.Next!=nil{count++cursor =cursor.Next}//// 相等不需要移动k =k%countif k==0 {return head}//当前是尾结点 // 头尾相连 循环链表cursor.Next = head// 找到需要分割的节点/*1 2 3 4 第0次4 1 2 3 第1次3 4 1 2 第2次*/l :=count-(k%count)pre := headfor i:=0;i<l-1;i++{pre = pre.Next}newHead := pre.Nextpre.Next = nilreturn newHead}func main() {one :=&ListNode{Val: 1,}two :=&ListNode{Val: 2,}three :=&ListNode{Val: 3,}four :=&ListNode{Val: 4,}five :=&ListNode{Val: 5,}one.Next = twotwo.Next = threethree.Next= fourfour.Next = fiveh:=rotateRight(one,2)for h!=nil{fmt.Println(h.Val)h =h.Next}}

