Created
August 6, 2021 23:21
-
-
Save jlgm/69ac5f9f49657adea3b6b095e8616160 to your computer and use it in GitHub Desktop.
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 reverseList(cur *ListNode, k int) (*ListNode, *ListNode) { | |
if cur.Next == nil || k == 1 { | |
return cur, cur | |
} | |
tmp, head := reverseList(cur.Next, k-1) | |
tmp.Next = cur | |
cur.Next = nil | |
return cur, head | |
} | |
func reverseKGroup(head *ListNode, k int) *ListNode { | |
var ans *ListNode | |
var lastTail *ListNode | |
it, cnt := head, 0 | |
for it != nil { | |
cnt++ | |
if cnt%k == 0 { | |
tmp := it.Next | |
tail, newHead := reverseList(head, k) | |
if ans == nil { | |
ans = newHead | |
} | |
if lastTail == nil { | |
lastTail = tail | |
} else { | |
lastTail.Next = newHead | |
lastTail = tail | |
} | |
tail.Next = tmp | |
head = tmp | |
it = tmp | |
} else { | |
it = it.Next | |
} | |
} | |
return ans | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment