Leetcode 25 Reverse Nodes in k-Group

HowieLee59發表於2018-10-21

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list's nodes, only nodes itself may be changed.

1)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//一定要注意好節點的next指標的指向
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode node = new ListNode(0);
        ListNode list = head;
        ListNode n = node;//標記下節點,直接返回
        Stack<Integer> stack1 = new Stack<>();//當剩餘的還大於K的時候
        Stack<Integer> stack2 = new Stack<>();//當最後的個數不到k個的時候
        while(list != null){
            while(stack1.size() < k && list != null){
                stack1.push(list.val);
                list = list.next;
            }//首先壓入棧
            if(stack1.size() == k){
                while(!stack1.isEmpty()){
                    node.next = new ListNode(stack1.pop());
                    node = node.next;
                }
            }else if(stack1.size() < k){
                while(!stack1.isEmpty()){
                    stack2.push(stack1.pop());
                }
                while(!stack2.isEmpty()){
                    node.next = new ListNode(stack2.pop());
                    node = node.next;
                }
            }
        }
        return n.next;
    }
}

2)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
//top1的解法總是這麼強(膜拜)
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode p = head;
        int i = 0;
        while(p != null && i < k) {
            p = p.next;
            i++;
        }
        if(i == k) {
            p = reverseKGroup(p, k);
            while(i-- > 0) {
                ListNode tmp = head.next;
                head.next = p;
                p = head;
                head = tmp;
            }
            head = p;
        }
        return head;
    }
}

 

相關文章