25. 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.
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,思路简单但是实现起来挺复杂的。。下面的代码我不该贴上来的,几乎是抄的。。自己没有完整写过一遍。只是觉得在这样的题目上浪费时间听不值得的。坐了一天,脑子昏昏沉沉的,眼睛很累。状态好差。。回家睡觉了。

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;
}
}

http://blog.csdn.net/linhuanmars/article/details/19957455

你可能感兴趣的:(25. Reverse Nodes in k-Group)