138. 复制带随机指针的链表 golang
生活随笔
收集整理的這篇文章主要介紹了
138. 复制带随机指针的链表 golang
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
138. 復制帶隨機指針的鏈表
這個題結構體特殊,需要更改上一篇博客的node結構體
給定一個鏈表,每個節點包含一個額外增加的隨機指針,該指針可以指向鏈表中的任何節點或空節點。
要求返回這個鏈表的 深拷貝。
我們用一個由 n 個節點組成的鏈表來表示輸入/輸出中的鏈表。每個節點用一個 [val, random_index] 表示:
val:一個表示 Node.val 的整數。
random_index:隨機指針指向的節點索引(范圍從 0 到 n-1);如果不指向任何節點,則為 null 。
示例 1:
輸入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
輸出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
輸入:head = [[1,1],[2,1]]
輸出:[[1,1],[2,1]]
示例 3:
輸入:head = [[3,null],[3,0],[3,null]]
輸出:[[3,null],[3,0],[3,null]]
示例 4:
輸入:head = []
輸出:[]
解釋:給定的鏈表為空(空指針),因此返回 null。
提示:
-10000 <= Node.val <= 10000
Node.random 為空(null)或指向鏈表中的節點。
節點數目不超過 1000 。
解法
/*** Definition for a Node.* type Node struct {* Val int* Next *Node* Random *Node* }*/ func copyRandomList(head *Node) *Node {//1->2(4)->3->4->nilif head == nil {return nil}//1->1->2->2->3->3->4->4res := copyNextPoint(head)//1->1->2(4)->2(4)->3->3->4->4res = copyRandomPoint(res)//1->2(4)->3->4->nilres = listCut(res)return res }func copyNextPoint(head *Node) *Node {temp := new(Node)temp.Next = headp := headfor p != nil {tmp := new(Node)tmp.Val = p.Valtmp.Next = p.Nextp.Next = tmpp = p.Next.Next}return temp.Next }func copyRandomPoint(head *Node) *Node {temp := new(Node)temp.Next = headp := headfor p != nil {if p.Random != nil {temp_random := p.Nexttemp_random.Random = p.Random.Next}p = p.Next.Next}return temp.Next }func listCut(head *Node) *Node {temp := new(Node)res := tempfor old := head; old != nil;{res.Next = old.Nextold.Next = res.Next.Nextold, res = old.Next, res.Next}return temp.Next }總結
以上是生活随笔為你收集整理的138. 复制带随机指针的链表 golang的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地下城堡3手游铸魔人怎么样
- 下一篇: 160. 相交链表 golang