<LinkedList> (hard + 高)25

25. Reverse Nodes in k-Group

用栈的形式存储k个节点并反转,一个是用来入栈分段的,一个是用来出栈翻转的

空间复杂度O( N ) 

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null) return null;
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        ListNode next = dummy.next;
        while(next != null){
            for(int i = 0; i < k && next != null; i++){
                stack.push(next);
                next = next.next;
            }
            if(stack.size() != k) return dummy.next;
            while(stack.size() != 0){
                cur.next = stack.pop();
                cur = cur.next;
            }
            cur.next = next;
        }
        return dummy.next;
    }
}

方法二:每次调用函数都翻转一段链表。

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null) return null;
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        while(pre != null){
            pre = reverse(pre, k);
        }
        return dummy.next;
    }
    
    public ListNode reverse(ListNode pre, int k){
        ListNode last = pre;
        for(int i = 0; i < k + 1; i++){
            last = last.next;
            if(i != k && last == null) return null;
        }
        ListNode tail = pre.next;
        ListNode cur = pre.next.next;
        while(cur != last){
            ListNode next = cur.next;
            cur.next = pre.next;
            pre.next = cur;
            tail.next = next;
            cur = next;
        }
        return tail;
    }
}
posted @ 2020-01-13 11:29  阿飞哦  阅读(103)  评论(0编辑  收藏  举报