https://leetcode.com/problems/reverse-nodes-in-k-group/
Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
下面的代码是,先找到k个node,然后调用reverse函数,这个函数将会把head和tail之间的所有node做reverse,但不包含head和tail,返回reverse后tail之前的那个node。
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null || head.next==null) return head;
if(k==1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode before = dummy;
ListNode after = dummy;
while(after != null){
int t = k;
while(t>0){
if(after == null) return dummy.next;
after = after.next;
t--;
}
if(after == null) return dummy.next;
before = reverse(before, after.next);
after = before;
}
return dummy.next;
}
public ListNode reverse(ListNode head, ListNode tail){
if(head==tail || head.next==tail || head.next.next==tail) return head;
//reverse the nodes between head and tail, not include head and tail
ListNode tvs = head.next.next;
ListNode last = head.next;
while(tvs!=tail){
last.next = tvs.next;
tvs.next = head.next;
head.next = tvs;
tvs = last.next;
}
return last;
}
}