Leetcode Golang 61. Rotate List.go

2019-04-12 10:57:23 浏览数 (1)

版权声明:原创勿转 https://cloud.tencent.com/developer/article/1412864

思路

先把list变成一个环,然后转到指定位置

注意有个取模的处理

code

代码语言:javascript复制
func rotateRight(head *ListNode, k int) *ListNode {
	if head == nil || head.Next == nil || k == 0 {
		return head
	}
	len := 1
	tail := head
	for tail.Next != nil {
		tail = tail.Next
		len  
	}
	tail.Next = head //变成一个环
	k = k % len      //因为是个环,所以不用转超过一圈
	for i := 0; i < len-k; i   {
		tail = tail.Next
	}
	head = tail.Next
	tail.Next = nil
	return head
}

0 人点赞