2.2.9 Reverse Nodes in K-group

来源:互联网 发布:上海软件测试培训 编辑:程序博客网 时间:2024/05/28 15:07

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.NullPointerExceptionLast 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; }


0 0