Advertisement
Iam_Sandeep

Linked lis deepcopy O(1)

Jul 4th, 2022
945
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. problem='https://practice.geeksforgeeks.org/problems/clone-a-linked-list-with-next-and-random-pointer/1'
  2. class Solution:
  3.     def copyList(self, head):
  4.         cur=head
  5.         while cur:
  6.             t=cur.next#next node
  7.             cp=Node(cur.data)#copy node
  8.             cur.next=cp#setting up copied nodes
  9.             cp.next=t
  10.             cur=cp.next
  11.         cur=head
  12.         while cur:#arrange random pointers
  13.             cur.next.arb=cur.arb.next if cur.arb else None
  14.             cur=cur.next.next if cur.next else None
  15.         cur=head
  16.         t=ans=head.next
  17.         while cur:#setup ans chain
  18.             cur.next=cur.next.next if cur.next else None
  19.             t.next=t.next.next if t.next else None
  20.             cur,t=cur.next,t.next
  21.         return ans
  22.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement