首页 > 代码库 > LeetCode:Reverse Nodes in k-Group
LeetCode:Reverse Nodes in k-Group
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=2,这个k是随意取。其实在这个代码里面,函数hasKNode(ListNode node,int k),看看node后面是否有n个结点。有就返回true.而nextKNode(ListNode start,int k)返回start后第K的结点,也就是在此次reverse的最后一个结点。
其实想法很简答,将k个元素,从最后一个结点开始,指向前面一个结点,将其实结点指向下一组的开始结点。
For k = 3, you should return: 3->2->1->4->5
其实一开始1->2->3->4->5:1->2<-3 4->5: 1<-2<-3 4->5:3->2->1->4->5
public class Solution {
public ListNode reverseKGroup(ListNode head, int k)
{
ListNode start = head;
if(!hasKNode(start,k))
return head;
ListNode last = nextKNode(start,k);
head = last;
ListNode former = start;
ListNode nextNode = last.next;
int i = k - 1;
while(i>0)
{
last.next = nextKNode(start,i);
last = last.next;
i--;
}
start.next = nextNode;
while(hasKNode(nextNode,k))
{
former = reverseKNode(former,k);
nextNode = former.next;
}
return head;
}
public ListNode reverseKNode(ListNode former,int k)
{
ListNode node = former.next;
ListNode nextNode;
if(hasKNode(node,k))
{
ListNode last = nextKNode(node,k);
former.next = last;
nextNode = last.next;
int i = k - 1;
while(i>0)
{
last.next = nextKNode(node,i);
last = last.next;
i--;
}
node.next = nextNode;
}
else
{
return null;
}
return node;
}
public boolean hasKNode(ListNode start,int k)
{
ListNode node = start;
int i = 1;
while(node != null&&i<k)
{
node = node.next;
i++;
}
if(node != null&&i==k)
{
return true;
}
return false;
}
public ListNode nextKNode(ListNode start,int k)
{
ListNode node = start;
int i = 1;
while(node!=null&&i<k)
{
node=node.next;
i++;
}
return node;
}
}