找倒数第K个节点的变形,需要注意的是k大于链表的长度,需要得到链表的长度L后:K=K%L;
package main
import . "nc_tools"
/*
* type ListNode struct{
* Val int
* Next *ListNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
func rotateLinkedList( head *ListNode , k int ) *ListNode {
if head == nil {
return head
}
h := head
num := 0
for h != nil {
h = h.Next
num++
}
k = k%num
kNode,last := findEKListNode(head,k+1)
last.Next = head
res := kNode.Next
kNode.Next = nil
return res
}
func findEKListNode( head *ListNode , k int) (*ListNode,*ListNode){
fast,slow,last := head,head,head
i := 1
for fast != nil {
last = fast
fast = fast.Next
if i > k {
slow = slow.Next
}
i++
}
return slow,last
}