LintCode(105) 複製帶隨機指標的鍊錶

2021-07-13 06:04:39 字數 1816 閱讀 3881

複製帶隨機指標的鍊錶

給出乙個鍊錶,每個節點包含乙個額外增加的隨機指標可以指向鍊錶中的任何節點或空的節點。

返回乙個深拷貝的鍊錶。 

乙個經典題目,思想就是在複製每個原節點鏈結其後,然後依次新增新節點的random指標。

遍歷複製後的鍊錶,刪除原節點。

就不詳述了,看**,重點是練習python實現~~~

# definition for singly-linked list with a random pointer.

# class randomlistnode:

# def __init__(self, x):

# self.label = x

# self.next = none

# self.random = none

class solution:

# @param head: a randomlistnode

# @return: a randomlistnode

def copyrandomlist(self, head):

# write your code here

if head is none:

return none

p = head

while p is not none:

r = p.next

node = randomlistnode(p.label)

node.next = p.next

p.next = node

p = r

p = head

q = p.next

if q is none:

print("none")

while p is not none and q is not none:

if p.random is not none:

q.random = p.random.next

p = q.next

if p is not none:

q = p.next

ret = head.next

del head

q = ret

while q.next is not none:

p = q.next

q.next = p.next

del p

q = q.next

return ret

github -- python完整**

/**

* definition for singly-linked list with a random pointer.

* struct randomlistnode

* };

*/class solution //if

randomlistnode *p = head;

while(p != null)

//while

p = head;

randomlistnode *q = head->next;

while(p && q)

p = q->next;

if(p)

}//while

randomlistnode *ret = head->next;

delete head;

q = ret;

while(q->next)

//while

return ret;

}};

github -- c++**

105 複製帶隨機指標的鍊錶

中文english 給出乙個鍊錶,每個節點包含乙個額外增加的隨機指標可以指向鍊錶中的任何節點或空的節點。返回乙個深拷貝的鍊錶。可否使用o 1 的空間 hashmap寫法,o n 時間複雜度 definition for singly linked list with a random pointer...

lintcode,複製帶隨機指標的鍊錶

給出乙個鍊錶,每個節點包含乙個額外增加的隨機指標可以指向鍊錶中的任何節點或空的節點。返回乙個深拷貝的鍊錶。一刷ac 解題思路 用map儲存節點和label,每次判斷節點是否存在然後插入map,拷貝時把map對應節點的label取出來。definition for singly linked list...

複製帶隨機指標的鍊錶

給出乙個鍊錶,每個節點包含乙個額外增加的隨機指標可以指向鍊錶中的任何節點或空的節點。返回乙個深拷貝的鍊錶。public randomlistnode copyrandomlist randomlistnode head hashmapmap new hashmap randomlistnode du...