LeetCode 25. Reverse Nodes in k-Group

描述[Hard]

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

分析

  • 首先需要一个方法hasKNodes(ListNode l, int k),判断是否有足够的(K个)ListNode能够被逆转。
  • 然后需要一个方法reverveKNode(ListNode l, int k),将以head为开头的K个节点。
  • 最后用特定的调用,将上述两个方法结合起来。

代码

class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
}


public class ReversedKNode {

    public static void printList(ListNode l){
        StringBuilder sb = new StringBuilder();
        while (l != null && l.next != null){
            sb.append(l.val);
            sb.append(" => ");
            l = l.next;
        }
        sb.append(l.val);
        System.out.println(sb.toString());
    }

    //返回k个节点倒置后的头和尾
    private ListNode[] reverveKNode(ListNode head, int k){
        Stack<ListNode> stack = new Stack<>();
        for (int i = 0; i < k; i++){
            ListNode temp = head.next;
            head.next = null;
            stack.push(head);
            head = temp;
        }
        ListNode newHead = stack.pop();
        ListNode tem = newHead;
        while(!stack.isEmpty()){
            newHead.next = stack.pop();
            newHead = newHead.next;
        }
        newHead.next = head;
        return new ListNode[]{tem, newHead};
    }

    //判断是否有足够的节点可以供逆转
    private boolean hasKNodes(ListNode head, int k){
        int num = 0;
        while (head != null){
            head = head.next;
            num++;
            if (num == k){
                return true;
            }
        }
        return false;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if(!hasKNodes(head, k)){
            return head;
        }
        ListNode[] results = reverveKNode(head, k);
        ListNode newHead = results[0];
        ListNode next = results[1];
        next.next = reverseKGroup(next.next, k);
        return newHead;
    }

    public static void main(String...args){
        ListNode one = new ListNode(1);
        ListNode two = new ListNode(2);
        ListNode thr = new ListNode(3);
        ListNode fur = new ListNode(4);
        ListNode fiv = new ListNode(5);
        one.next = two;
        two.next = thr;
        thr.next = fur;
        fur.next = fiv;

        ListNode res = new ReversedKNode().reverseKGroup(one, 6);
        printList(res);
    }

}
点赞