Reverse Nodes in k-Group Leetcode

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,但思路并不难。首先翻转k个还是很容易的,然后用递归把第k+1个传到这个函数里。每次判断一下,如果linkedlist长度不到k,就直接返回不用翻转。
public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || getSize(head) < k) {
            return head;
        }
        
        ListNode pre = null;
        ListNode secondHead = head;
        ListNode current = head;
        int count = 0;
        while (count < k) {
            head = head.next;
            current.next = pre;
            pre = current;
            current = head;
            count++;
        }
        secondHead.next = reverseKGroup(head, k);
        return pre;
    }
    public int getSize(ListNode head) {
        int size = 0;
        while (head != null) {
            size++;
            head = head.next;
        }
        return size;
    }
}

改进版本如下,这个版本里不用遍历整个list来求length,所以快了很多。

这个的思路是,直接找到第k+1个node,放到递归里去,返回新的list的head。再reverse新的list前面的值,接在新的list的前面。

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode current = head;
        int count = 0;
        while (current != null && count != k) {
            current = current.next;
            count++;
        }
        if (count == k) {
            current = reverseKGroup(current, k);
            while (count > 0) {
                ListNode tmp = head.next;
                head.next = current;
                current = head;
                head = tmp;
                count--;
            }
        } else {
            return head;
        }
        return current;
    }
}

还有non-recursive的方法,懒得写了。。。思路就是,写一个helper function,参数是begin和end,reverse这之间的node,返回接到原来的list上。有机会再回顾吧。。。 

posted @ 2017-04-06 02:22  璨璨要好好学习  阅读(108)  评论(0编辑  收藏  举报