1. 程式人生 > >【LeetCode】25. Reverse Nodes in k-Group - Java實現

【LeetCode】25. Reverse Nodes in k-Group - Java實現

文章目錄

1. 題目描述:

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.

2. 思路分析:

題目的意思是將一個連結串列按照順序每k個進行翻轉。

此題可以新建一個方法用於翻轉含有k個節點的連結串列區間。然後在主方法中遍歷整個列表,用一個計數器表示遍歷的節點數,當達到k個時呼叫一下新建的那個方法對這k個節點進行翻轉,然後將計數器清為0,繼續遍歷,以此類推。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static ListNode reverseKGroup(ListNode head, int k) {
    // 構建一個頭結點,方便連線最後結果
    ListNode dummy = new ListNode
(-1); dummy.next = head; // 指向翻轉區間第一個節點的前一個節點 ListNode pre = dummy; // 指向翻轉區間的第一個節點 ListNode first = pre.next; // 用於遍歷的當前節點指標 ListNode cur = first; int cnt = 0; while (cur != null) { cnt++; if (cnt == k) { ListNode last = cur; pre.next = reverseOneGroup(first, last); // 注意此處的first節點已經是翻轉後的最後一個節點了 pre = first; first = pre.next; cur = first; cnt = 0; } else { cur = cur.next; } } return dummy.next; } /** * 用於翻轉一個區間內的連結串列 */ private static ListNode reverseOneGroup(ListNode first, ListNode last) { while (first != last) { ListNode cur = first; first = first.next; cur.next = last.next; // last節點作為翻轉後的第一個節點 last.next = cur; } return last; }