《leetCode》:Reverse Nodes in k-Group
程序员文章站
2021-11-26 20:04:25
...
题目:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// head - head-pointer to direct part,
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
head.next = curr; // preappending "direct" head to the reversed list
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
head = curr;
}
return head;
}
推荐阅读
-
LeetCode --- 783. Minimum Distance Between BST Nodes 解题分析
-
Leetcode 7. Reverse Integer
-
LeetCode:7. Reverse Integer
-
【leetcode】7. Reverse Integer
-
Leetcode 1530. Number of Good Leaf Nodes Pairs (python)
-
Leetcode 1519. Number of Nodes in the Sub-Tree With the Same Label (python)
-
LeetCode 1519. Number of Nodes in the Sub-Tree With the Same Label
-
[leetcode] 1315. Sum of Nodes with Even-Valued Grandparent
-
【Leetcode】190. Reverse Bits(二进制数反转)
-
Leetcode——24. Swap Nodes in Pairs