Skip to content

Instantly share code, notes, and snippets.

@amraks
Last active June 23, 2017 02:32
Show Gist options
  • Save amraks/2938444cfd1cec894e52a2526aed7530 to your computer and use it in GitHub Desktop.
Save amraks/2938444cfd1cec894e52a2526aed7530 to your computer and use it in GitHub Desktop.
Clone linked list
class Node(object):
def __init__(self, data):
self.data = data
self.next = None
def clone(cur):
start = cur
prev = None
new_list_head = None
while True:
new = Node(cur.data)
if not new_list_head:
new_list_head = new
if prev:
prev.next = new
cur = cur.next
prev = new
if cur == start:
break
prev = new
return new_list_head
n1 = Node(10)
n2 = Node(20)
n3 = Node(30)
n4 = Node(40)
n1.next = n2
n2.next = n4
n3.next = n1
n4.next = n3
s = n = clone(n1)
while True:
print(n.data)
n = n.next
if s == n:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment