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个为一组,基本操作时反转单链表,每组的前驱需要保存,做完反转操作以后本组原头结点成为下一组的前驱,后继也可以在反转链表的操作中找到,回忆反转单链表,最后p1是新头结点,p2访问到反转前的尾节点下一个位置,在这里即可以作为下一组反转的开始节点。
这样的操作需要多少次,可以先遍历得到总节点数以后计算出来。
public class Solution {
ListNode pre=null;
ListNode nextstart=null;
public ListNode reverseKGroup(ListNode head, int k)
{
if(k<2)
return head;
int cnt=0;
ListNode n=head;
while(n!=null)
{
cnt++;
n=n.next;
}
ListNode dummy=new ListNode(-1);
dummy.next=head;
pre=dummy;
n=head;
nextstart=head;
for(int i=0;i<cnt/k;i++)
{
reverselist(nextstart, k-1);
}
pre.next=nextstart;
return dummy.next;
}
public void reverselist(ListNode head,int times)
{
ListNode p1=head;
ListNode p2=p1.next;
ListNode p3=null;
int count=0;
while(p2!=null)
{
p3=p2.next;
p2.next=p1;
p1=p2;
p2=p3;
count++;
if(count==times)
{
pre.next=p1;
pre=head;
nextstart=p2;
return ;
}
}
}
}
--------------------------------------------------------------------------------------------------------------------------------
递归版本,摘自https://discuss.leetcode.com/topic/7126/short-but-recursive-java-code-with-comments
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
// head - head-pointer to direct part,
// curr - head-pointer to reversed part;
while (count-- > 0) { // reverse current k-group:
ListNode tmp = head.next; // tmp - next head in direct part
head.next = curr; // preappending "direct" head to the reversed list
curr = head; // move head of reversed part to a new node
head = tmp; // move "direct" head to the next node in direct part
}
head = curr;
}
return head;
}
1->2 ->3->4->5