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
java代码
/**
* 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) {
ListNode preHead = new ListNode(0);
preHead.next = head;
ListNode pre = preHead;
int count = 1;
ListNode first = head,last=head;
while(first!=null&&last!=null){
count=1;
while(count < k && last.next!=null){
last = last.next;
count++;
}
if (count < k){
break;
}
ListNode back = last.next;
ListNode re = reverse(first,last);
pre.next = re;
pre = first;
first = back;
last = back;
}
return preHead.next;
}
public ListNode reverse(ListNode first,ListNode last){
ListNode back = last.next;
ListNode cur = first;
ListNode next = cur.next;
ListNode pre = null;
while(pre!=last){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
// if(pre==last){
// break;
// }
}
cur = pre;
while(cur.next!=null){
cur=cur.next;
}
cur.next=back;
return pre;
}
}
go代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseKGroup(head *ListNode, k int) *ListNode {
var preHead *ListNode = &ListNode{
Val:0,
Next:head,
}
var pre *ListNode = preHead
var first *ListNode = head
var last *ListNode = head
var count int = 1
for first!=nil&&last!=nil{
count = 1
for count<k&&last.Next!=nil{
count++
last=last.Next
}
if count<k{
break
}
back:=last.Next
re:=reverse(first,last)
pre.Next = re
pre = first
first = back
last = back
}
return preHead.Next
}
func reverse(f *ListNode,l *ListNode) *ListNode{
var back *ListNode = l.Next
var pre *ListNode = nil
var cur *ListNode = f
var next *ListNode = f.Next
for pre!=l{
next = cur.Next
cur.Next = pre
pre = cur
cur = next
}
cur = pre
for cur.Next!=nil{
cur = cur.Next
}
cur.Next = back
return pre
}