【LeetCode-面試演算法經典-Java實現】【025-Reverse Nodes in k-Group(單鏈表中k個結點一組進行反轉)】,leetcode--java
【025-Reverse Nodes in k-Group(單鏈表中k個結點一組進行反轉)】【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】原題
Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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,每K個結點進行反轉,如果最後的結點數不足K個就保持原來的連結順序不變。
解題思路
用一個指標記錄連結好的鏈表的最後一個結點(tail),用一個指標記錄上一次連結好的部分的最後一個結點(head)對未鏈表的結點在head處進行尾插法,插k個元素,再將head移動到tail處,tail重新記錄鏈表的尾結點,直到所有的元素都進行了操作。如果最後的一組元素不足k個,因為進行過尾插法,所以還要進行還原,對最後的head元素進行尾插法就可以了
代碼實現
結點類
public class ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
演算法實作類別
public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if (k <= 1) { return head; } ListNode root = new ListNode(0); // 分組的頭一個元素的前驅 ListNode groupHead = root; // 當前要處理的結點 ListNode curr = head; // 處理好的鏈表的尾結點 ListNode groupTail = head; // 當前要處理的結點的後繼 ListNode next; // 對每個組,處理了多少個結點 int count = 0; while (curr != null) { // 如果是分組的第一個元素就記錄它 if (count == 0) { groupTail = curr; } // 記錄處理的元素個數 count++; // 記錄下一個待處理結點 next = curr.next; // 進行尾插法操作 curr.next = groupHead.next; groupHead.next = curr; curr = next; // 已經處理完了k個結點,分組頭的前驅移動到最後一個連結好的結點 if (count == k) { groupHead = groupTail; // 計數器歸零 count = 0; } } // 說明結點個數不是k的整數倍,將最後不是整數倍的個元素的結點, // 再次使用尾插法進行還原 if (count != 0) { curr = groupHead.next; groupHead.next = null; while (curr != null) { next = curr.next; curr.next = groupHead.next; groupHead.next = curr; curr = next; } } return root.next; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47034983】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。