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
這題是hard,思路簡單但是實現(xiàn)起來挺復(fù)雜的。。下面的代碼我不該貼上來的,幾乎是抄的。。自己沒有完整寫過一遍。只是覺得在這樣的題目上浪費時間聽不值得的。坐了一天,腦子昏昏沉沉的,眼睛很累。狀態(tài)好差。。回家睡覺了。
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) return head;
int count = 0;
ListNode dummy = new ListNode(-1);
dummy.next = head ;
//pre永遠指向k pairs開始的前一位
ListNode pre = dummy ;
ListNode cur = head ;
while (cur!=null) {
ListNode next = cur.next ;
count ++ ;
if(count == k){
pre = reverseList1(pre , next);
count=0;
}
cur = next ;
}
return dummy.next;
}
private ListNode reverseList1(ListNode pre, ListNode end)
{
if(pre==null || pre.next==null)
return pre;
ListNode head = pre.next;
ListNode cur = pre.next.next;
while(cur!=end)
{
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = next;
}
//返回end的前一位的方法
head.next = end;
return head;
}
}