25. Reverse Nodes in k-Group
题目
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
}
}
描述
给定一个单链表,每k个节点做一次反转,并返回反转过的链表。
分析
基本思路就是每k个节点拆分出一个子链表并且做反转,需要注意反转后子链表的前后要和其它部分正确衔接。给出循环和递归两种解法。
解法1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0), curr = head, prev = dummy, start, end;
dummy.next = head;
int i = 0;
while (curr != null) {
if (++i % k == 0) {
start = prev.next;
end = curr.next;
curr.next = null;
prev.next = reverse(start);
start.next = end;
prev = start;
curr = end;
} else {
curr = curr.next;
}
}
return dummy.next;
}
private ListNode reverse(ListNode head) {
ListNode prev = null, curr = head, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
解法2
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head, prev = null;
int i = 0;
while (i < k && curr != null) {
i++;
prev = curr;
curr = curr.next;
}
if (i < k) {
return head;
} else {
prev.next = null;
reverse(head);
head.next = reverseKGroup(curr, k);
return prev;
}
}
private ListNode reverse(ListNode head) {
ListNode prev = null, curr = head, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}