Leetcode解題報(bào)告——25. 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

題目大意:
給定一個(gè)鏈表及一個(gè)變量K,每K個(gè)節(jié)點(diǎn)進(jìn)行一次翻轉(zhuǎn)

解題思路:
將原鏈表按K個(gè)節(jié)點(diǎn)分別進(jìn)行翻轉(zhuǎn),再拼接,具體做法:

  1. 判斷該鏈表是否為空,或長(zhǎng)度小于K——返回該鏈表
  2. 翻轉(zhuǎn)前K個(gè)節(jié)點(diǎn)
  3. 將剩余的節(jié)點(diǎn)作為新鏈表,進(jìn)行迭代
  4. 返回新鏈表

代碼如下:

public   ListNode reverseKGroup(ListNode head, int k) {
        if(k<=1 || head == null) return head;
        int i = 0;
        ListNode  node = new ListNode(0);
        node.next = head;
        while(node.next != null) {
            i++;
            node = node.next;
        }
        if(i < k) return head;

        ListNode var = head;
        i = k;
        while(i-- >1){
            ListNode temp = var.next;
            var.next = temp.next;
            temp.next = head;
            head = temp;
        }
        var.next = reverseKGroup(var.next,k);
        return head;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容