【Leetcode】25.Reverse Nodes in k-Group

於淼發表於2018-03-05

Question:

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

Tips:

給定一個連結串列,每k個結點進行一次翻轉,最後若剩餘不足k個結點,不進行操作,直接接在後面。

思路:

舉例說1->2->3->4->5->6;  k=4;

設定一個int型變數count,一個指標指向頭結點。每走過一個結點count++。當count%k!=0 指標繼續後移,如果count%k==0 則從頭結點開始,到head.next結束,傳入reverse函式,進行翻轉。注意插入的部分連結串列,第一個跟最後一個不進行翻轉,傳入只是為了將翻轉的連結串列連線起來。

進行第一次reverse 傳入的連結串列是(-1->1->2->3->4->5).返回(-1->4->3->2->1->5)

程式碼:

public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null ||head.next==null ||k==1) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode begin = dummy;
        int count=0;
        while (head != null) {
            count++;
            if(count%k==0){
                //頭結點+需要反轉的一整組結點+下一組的第一個結點,全部傳入reverse
                begin=reverse(begin,head.next);
                head=begin.next;
            }else{
                head=head.next;
            }
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode begin, ListNode end) {
        ListNode pre=begin;
        ListNode cur=begin.next;
        //first記錄該組第一個結點,反轉後為最後一個結點。
        ListNode first=cur;
        while(cur!=end){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        //pre為該組翻轉後得第一個結點,之後還需要將pre接在begin之後。
        begin.next=pre;
        //cur為下一組的結點,需要將其接在該組翻轉後最後一個結點之後。
        first.next=cur;
        return first;
    }

相關文章