-
Notifications
You must be signed in to change notification settings - Fork 0
/
linklist.py
71 lines (60 loc) · 1.45 KB
/
linklist.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class LinkNode(object):
def __init__(self, value):
self.value = value
self.next = None
def insert(self, value):
if self.next:
self.next.insert(value)
else:
self.next = LinkNode(value)
class LinkOperation(object):
def print(self, node):
p = node
while p:
print(p.value)
p = p.next
def reverse(self, node):
p = node.next
node.next = None
prev = node
while p:
next = p.next
p.next = prev
prev = p
p = next
return prev
def merge(self, link1, link2):
if link1.value < link2.value:
newlink = link1
link1 = link1.next
else:
newlink = link2
link2 = link2.next
p = newlink
while link1 and link2:
if link1.value < link2.value:
p.next = link1
link1 = link1.next
else:
p.next = link2
link2 = link2.next
p = p.next
if link1:
p.next = link1
else:
p.next = link2
return newlink
operation = LinkOperation()
link = LinkNode(3)
link.insert(4)
link.insert(5)
link.insert(7)
operation.print(link)
link1 = LinkNode(1)
link1.insert(2)
link1.insert(6)
link1.insert(8)
link1.insert(9)
operation.print(link1)
link3 = operation.merge(link1, link)
operation.print(link3)