標籤:單鏈表 複製 演算法 面試 java
【138-Copy List with Random Pointer(拷貝有隨機指標的單鏈表)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
題目大意
一個單鏈表包含一個指向任意結點或者null的結點指標,返回這個鏈表的深拷貝。
解題思路
第一步:複製結點,複製的結點放在待覆制的結點後,依然組成一個單鏈表
第二步:串接隨機指標
第三步:將原單鏈表與複製鏈表拆開
代碼實現
演算法實作類別
public class Solution { public RandomListNode copyRandomList(RandomListNode head) { if (head == null) { return null; } copyNode(head); linkRandomPointer(head); return splitList(head); } /** * 複製結點,複製的結點放在待覆制的結點後,依然組成一個單鏈表 * * @param head 鏈表頭 */ public void copyNode(RandomListNode head) { // 記錄當前要被複製的縝 RandomListNode node = head; while (node != null) { // 複製一個新的結點 RandomListNode copyNode = new RandomListNode(node.label); // 將結點串接到被複製的結點後,並且依然組成單鏈表 copyNode.next = node.next; node.next = copyNode; node = copyNode.next; } } /** * 串接隨機指標 * * @param head 鏈表頭 */ public void linkRandomPointer(RandomListNode head) { // 記錄當前要被複製的縝 RandomListNode node = head; while (node != null) { // 隨機指標有指向某個具體的結點 if (node.random != null) { // 串接node被複製結點的隨機指標 node.next.random = node.random.next; } // 指向下一個被複製的結點 node = node.next.next; } } /** * 將鏈表拆分,還原原來的鏈表,並且組裝拷貝的鏈表 * * @param head 鏈表頭 * @return 拷貝的新鏈表頭 */ public RandomListNode splitList(RandomListNode head) { // 新鏈表頭 RandomListNode copyHead = head.next; // 當前處理的被複製的結點 RandomListNode node = head; // 當前複製的結點 RandomListNode copy; while (node != null){ // 指向複製結點 copy = node.next; // node.next指向下一個被複製的結點 node.next = copy.next; // 下一個被複製的結點不為null if (node.next != null) { // copy.next指向下一個複製的結點 copy.next = node.next.next; } // node指向下一個要被處理的被複製結點 node = node.next; } return copyHead; }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47745459】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【138-Copy List with Random Pointer(拷貝有隨機指標的單鏈表)】