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
题目意思很明确,即每k个数反转,如果剩余数量小于k,则不反转。
基本思路是,每k个数反转一次,然后将反转后的链表连接在一起即可。由于题目要求空间复杂度为O(1),因此不能再创建新的链表,只能在原链表基础上完成反转。
程序如下所示:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode[] reverse(ListNode node, int k, int len){
if (k > len){
return new ListNode[]{node, null};
}
ListNode retNode = null;
ListNode tmp = null;
int cnt = 0;
while (node != null){
cnt ++;
tmp = node.next;
node.next = retNode;
retNode = node;
node = tmp;
if (cnt == k){
break;
}
}
return new ListNode[]{retNode, tmp};
}
private int getListLen(ListNode head){
int len = 0;
while (head != null){
len ++;
head = head.next;
}
return len;
}
public ListNode reverseKGroup(ListNode head, int k) {
ListNode tmp = null, retHead = null, linkNode = new ListNode(0);
boolean tag = false;
int len = getListLen(head), remainLen = len;
while (head != null){
tmp = head;
ListNode[] array = reverse(head, k, remainLen);
remainLen -= k;
linkNode.next = array[0];
if (!tag){
retHead = array[0];
tag = true;
}
linkNode = tmp;
head = array[1];
}
return retHead;
}
}