leetcode-25 Reverse Nodes in k-Group,leetcode-25k-group
問題描述:
Given a linked list, reverse the nodes of a linkedlist k at a time and return its modifiedlist.
If the number of nodes is not a multiple of k then left-out nodes in the end shouldremain as it is.
You may not alter the values in the nodes, only nodesitself 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
問題分析:
該問題可以轉化為反轉鏈表的子問題
(http://blog.csdn.net/woliuyunyicai/article/details/45027883)
根據題設需要依據k的值將原鏈表分為多個分組進行反轉;而且要注意前後鏈表之間的串連。因此需要記錄前後分組資訊,記錄前一個分組preGroup的尾節點,記錄後一個分許nextGroup的前端節點,然後再將當前分組反轉後的鏈表與前後鏈錶鏈接到一起。
代碼:
class ListNode { int val; ListNodenext; public ListNode (int val) { this.val = val; }} public classSolution { public ListNodereverseKGroup(ListNode head, int k) { // 直接返回結果的情況 if (k == 1 || head == null || head.next == null) return head; // 輔助節點,用以返回最終的結果 ListNoderesultNode = newListNode(0); resultNode.next = head; // 記下每一層的首節點,以及尾節點 ListNodetailNode = head; ListNodeheadNode = head; // 記下前一分組尾節點、後一分組的前端節點 ListNodepreGroup = resultNode; ListNodenextGroup = resultNode; // 每一層分組進行計數 int count = 1; while (tailNode != null) { // 到達該分組的尾部,對該分組進行反轉 if (count == k) { // 記錄下一分組的前端節點 nextGroup= tailNode.next; // 翻轉本分組鏈表 reverseList(headNode,tailNode); // 注意翻轉後tailNode則為當前分組的前端節點,headNode為尾節點 // 連結上一分組、下一分組 preGroup.next = tailNode; headNode.next = nextGroup; // 準備下一層迴圈 preGroup= headNode; headNode= nextGroup; tailNode= nextGroup; count= 1; continue; } count++; // 一直向下迴圈找到該分組的最後一個節點 tailNode= tailNode.next; } return resultNode.next; } // 反轉鏈表 private void reverseList(ListNodehead, ListNode tail) { ListNodepreNode = newListNode(0); preNode.next = head; ListNodesucNode = null; // 這裡不同於一般的反轉鏈表題目,這裡可以不用考慮為null的情況 while (preNode != tail) { sucNode= head.next; head.next = preNode; preNode= head; head= sucNode; } } }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。