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
Subscribe to see which companies asked this question
一刷没ac
解题思路:类似倒叙链表,需要注意的是根据长度判断是否需要reverse。
/**
* 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) {
if(head == null || k < 2) return head;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
boolean reverse = true;
while(true){
reverse = true;
ListNode copynode = head;
for(int i = 1; i < k; i++){
if(copynode != null) copynode = copynode.next;
if(copynode == null){
reverse = false;
break;
}
}
if(reverse){
ListNode l2 = copynode.next;
ListNode l1 = head;
copynode.next = null;
head = l2;
node.next = reverse(l1);
while(node.next != null) node = node.next;
}else {
node.next = head;
break;
}
}
return dummy.next;
}
public ListNode reverse(ListNode head){
if(head == null) return head;
ListNode dummy = new ListNode(0);
ListNode node = dummy;
while(head != null){
ListNode tmp = head.next;
ListNode next = node.next;
node.next = head;
head.next = next;
head = tmp;
}
return dummy.next;
}
}