Skip to content

Instantly share code, notes, and snippets.

@superzjn
Last active June 7, 2021 16:01
Show Gist options
  • Save superzjn/0d7128bb1517a13cd8fd64ec7444c3c7 to your computer and use it in GitHub Desktop.
Save superzjn/0d7128bb1517a13cd8fd64ec7444c3c7 to your computer and use it in GitHub Desktop.
[Reverse Nodes in k-Group] LeetCode 25 #LinkedList
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) return null;
ListNode start = head;
ListNode end = head;
for (int i = 0; i < k; i ++) {
// if there node number is less than k.
if (end == null) {
return head;
}
end = end.next;
}
ListNode newHead = reverse(start, end);
start.next = reverseKGroup(end, k);
return newHead;
}
public ListNode reverse(ListNode a, ListNode b) {
ListNode pre = null;
ListNode cur = a;
ListNode next = a;
while(cur != b) {
next = cur.next;
cur.next = pre;
pre = cur; // 更新指针位置
cur = next;
}
// 返回反转后的头结点
return pre;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment