2.2.9 Reverse Nodes in K-group

Link: https://oj.leetcode.com/problems/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.

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

我的思路:1 递归。同上一题。我的代码是:

但写不出来。再做。

public class Solution {
    //recursive
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode p = head;
        for(int i = 0; i < k-1; i++){
            if(p == null) return null;
            p = p.next;
        }
        head.next = reverseKGroups(p.next, k);
        //crease reverse links of k nodes
        reverse (head, k);
        return p;
    }
    
    public void createReverseLinks(ListNode head, int k){
        
    }
}

Approach II: Iterative

对每个节点,找出k-node group的时候要遍历一次。reverse这个k-node group要再遍历一次。所以对每个节点,遍历两次。所以Time = O(n)

Time: O(n), Space: O(1)

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy  = new ListNode(-1);
        dummy.next = head;
        ListNode preStart = dummy;
        while(preStart != null){
            ListNode start = preStart.next;
            ListNode end = preStart;//the end node of the k-node group
            for(int i = 0; i < k; i++){
                end = end.next;
                if(end == null) return dummy.next;
            }
            preStart.next = reverse(start, end);//connect preStart with the head of the reversed group
            //let preStart jump k nodes to reach the previous node of the next k-node group
            for(int i = 0; i < k; i++){
                preStart = preStart.next;
            }
        }
        return dummy.next;
    }
    
    public ListNode reverse(ListNode start, ListNode end){
        ListNode pre = start;
        ListNode cur = start.next;
        ListNode afterEnd = end.next;
        while(cur != afterEnd){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        start.next = afterEnd;
        return end;
    }
}
Note:

end 必须要初始化成preStart

for 循环里面的两句先后顺序不能反。

否则会出现错误:

Runtime Error Message: Line 35: java.lang.NullPointerException
Last executed input: {}, 1

 ListNode end = preStart;//the end node of the k-node group
 for(int i = 0; i < k; i++){
     end = end.next;
     if(end == null) return dummy.next;
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值