leetcode25~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.

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

採用了遞歸和非遞歸的解法,與上題類似,不過這是在K個節點進行翻轉。具體解釋在程序中。

public class ReverseNodeskGroup {

    //遞歸實現
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode curr = head;
        int count = 0;
        while(curr!=null && count!=k) {
            curr = curr.next;
            count++;
        }
        //找到curr爲k+1節點
        if(count==k) {
            //以curr作爲頭節點
            curr = reverseKGroup(curr, k);
            while(count-- >0) {
                ListNode tmp = head.next;
                head.next = curr;
                curr = head;
                head = tmp;
            }
            //curr此時爲翻轉後的第一個節點
            head = curr;
        }
        return head;
    }

    //非遞歸實現
    public ListNode reverseKGroup2(ListNode head, int k) {
        if(head==null || k==1) return head;
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode cur = head;
        int count = 0;
        while(cur!=null) {
            count++;
            //保存下一組的第一個節點
            ListNode next = cur.next;
            if(count==k) {
                //將變換之後的最後一個節點也就是變換之前的第一個節點賦值給pre
                pre = reverse(pre,next);
                count=0;
            }
            //這裏cur.next已經發生變化了,不能cur = cur.next
            cur = next;
        }
        return dummyNode.next;
    }

    private ListNode reverse(ListNode pre, ListNode next) {
        //需要改變pre指針,使之最後指向該組的最後一個節點
        //最後返回的是last指針,該組的第一個節點
        ListNode last = pre.next;
        ListNode curr = last.next;
        while(curr!=next) {
            last.next = curr.next;
            curr.next = pre.next;
            pre.next = curr;
            curr = last.next;
        }
        return last;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章