25 Reverse Nodes in k-Group
Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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 list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
每次先进行判断,剩下的元素是否足够,再转换。时间复杂度 o(n) ,空间复杂度 o(k)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode h = new ListNode(0,head);
ListNode t = h;
while(hasNext(t, k)){
t = modify(t, k);
for(int i=0;i<k;++i) t=t.next;
}
return h.next;
}
private ListNode modify(ListNode head, int k){
Deque<ListNode> stack = new LinkedList<>();
ListNode t = head.next;
for(int i=0;i<k;++i){
stack.push(t);
t=t.next;
}
ListNode tail = t;
t = head;
while(!stack.isEmpty()){
t.next = stack.pop();
t=t.next;
}
t.next = tail;
return head;
}
private boolean hasNext(ListNode head, int k){
for(int i=0;i<k;++i){
head=head.next;
if(head==null) return false;
}
return true;
}
}
空间复杂度 o(1) 的解法
public ListNode reverseKGroup(ListNode head, int k) {
if(k<=1) return head;
ListNode dummy=new ListNode();
dummy.next=head;
ListNode t=dummy,temp,a,b,c=null;
while(true){
temp=t;
for(int i=0;i<k;++i){
temp=temp.next;
if(temp==null) return dummy.next;
}
a=temp.next;
b=t.next;
c=b;
for(int i=0;i<k;++i){
c=c.next;
b.next=a;
a=b;
b=c;
}
temp=t.next;
t.next=a;
t=temp;
}
}