1. 程式人生 > >[LeetCode]25. Reverse Nodes in k-Group k個一組翻轉鏈表

[LeetCode]25. Reverse Nodes in k-Group k個一組翻轉鏈表

結點 遞歸 out 鏈表翻轉 ext its count nod link

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list‘s nodes, only nodes itself may be changed.

題目要求我們把給出的鏈表按K個一組翻轉,不足K個的不翻轉

這個可以看做是上一個題目兩兩翻轉節點的擴展,我們還是用遞歸來操作,先來確定下大致的處理過程

1.先從鏈表頭開始數k個節點,記錄個數,不滿k個的按k個處理

2.判斷上一步數出的節點個數,小於k則說明不用翻轉,直接返回head就行

3.節點個數等於k,說明需要反轉,利用3指針翻轉鏈表的做法,把這個k節點鏈表翻轉

4.前面幾步把k個節點翻轉了,剩下的節點遞歸調用該方法,然後返回翻轉後鏈表的頭結點

濃縮一下就是,先翻轉k個節點,然後通過遞歸把k個節點之後的鏈表也翻轉

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 
*/ class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode prev = null; ListNode cur = head; ListNode next = null; ListNode check = head; int canProceed = 0; int count = 0; // 檢查鏈表長度是否滿足翻轉 while (canProceed < k && check != null) { check = check.next; canProceed++; } // 滿足條件,進行翻轉 if (canProceed == k) { while (count < k && cur != null) { next = cur.next; cur.next = prev; prev = cur; cur = next; count++; } if (next != null) { // head 為鏈表翻轉後的尾節點 head.next = reverseKGroup(next, k); } // prev 為鏈表翻轉後的頭結點 return prev; } else { // 不滿住翻轉條件,直接返回 head 即可 return head; } } }

[LeetCode]25. Reverse Nodes in k-Group k個一組翻轉鏈表