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
Tips:
先找变到哪,再变。附上LintCode上m n的版本,这版是从m变到n位。
Code:
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head==null||head.next==null||k<2) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode tail = dummy;
ListNode prev = dummy;
int count;
while(true){
count =k;
while(count>0&&tail!=null){
count--;
tail=tail.next;
}
if (tail==null) break;//Has reached the end
head=prev.next;//for next cycle
// prev-->temp-->...--->....--->tail-->....
// Delete @temp and insert to the next position of @tail
// prev-->...-->...-->tail-->head-->...
// Assign @temp to the next node of @prev
// prev-->temp-->...-->tail-->...-->...
// Keep doing until @tail is the next node of @prev
while(prev.next!=tail){
ListNode temp=prev.next;//Assign
prev.next=temp.next;//Delete
temp.next=tail.next;
tail.next=temp;//Insert
}
tail=head;
prev=head;
}
return dummy.next;
}
}
LintCode:
public ListNode reverseBetween(ListNode head, int m , int n) {
// write your code
if (head == null){
return head;
}
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
ListNode preReverse = dummyNode;
for (int i = 0; i < m-1; i++){
if (preReverse.next == null) {
return null;
}
preReverse = preReverse.next;
}
ListNode first = preReverse.next;
ListNode postReverse = preReverse.next;
for (int i = 0; i < n-m; i++){
if (postReverse == null){
return null;
}
postReverse = postReverse.next;
}
preReverse.next = postReverse;
ListNode last = postReverse;
postReverse = postReverse.next;
for (int i = 0; i < n-m+1; i++){
ListNode temp = first.next;
first.next = postReverse;
postReverse = first;
first = temp;
}
return dummyNode.next;
}