Created
July 10, 2020 09:03
-
-
Save TonyWuLihu/406f607c2578049bf3df9718234e017d to your computer and use it in GitHub Desktop.
Leetcode rotate single linked list https://leetcode-cn.com/problems/rotate-list/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* type ListNode struct { | |
* Val int | |
* Next *ListNode | |
* } | |
*/ | |
func rotateRight(head *ListNode, k int) *ListNode { | |
//insertNode := &ListNode{0,nil} | |
//insertNode = head | |
var cursor *ListNode | |
var j int = 0 | |
if k >0 && head !=nil && head.Next !=nil{ | |
curNode := head | |
for curNode.Next.Next !=nil { | |
curNode = curNode.Next | |
j++ | |
} | |
count := j+2 | |
num := k%count | |
for i:=0; i< num; i++ { | |
curNode = head | |
for curNode.Next !=nil{ | |
if curNode.Next.Next != nil{ | |
curNode = curNode.Next | |
}else{ | |
cursor = curNode.Next | |
curNode.Next = nil | |
cursor.Next = head | |
head = cursor | |
} | |
} | |
} | |
} | |
return head | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment