-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmyclinklist.py
87 lines (77 loc) · 2.42 KB
/
myclinklist.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class CListNode:
def __init__( self, data ):
self.data = data
self.next = None
def traverse( listRef ):
curNode = listRef
done = listRef is None
while not done:
curNode = curNode.next
print curNode.data,
done = curNode is listRef
print ''
def searchCircularList( listRef, target ):
curNode = listRef
done = listRef is None
while not done:
curNode = curNode.next
if curNode.data == target:
return True
else:
done = curNode is listRef or curNode.data > target
return False
def sortedInsert( listRef, value ):
newNode = CListNode( value )
if listRef is None: # empty list
listRef = newNode
newNode.next = newNode
elif value < listRef.next.data: # insert in front
newNode.next = listRef.next
listRef.next = newNode
elif value > listRef.data: # insert in back
newNode.next = listRef.next
listRef.next = newNode
listRef = newNode
else:
preNode = None
curNode = listRef
done = listRef is None
while not done:
preNode = curNode
curNode = curNode.next
done = curNode is listRef or curNode.data > value
newNode.next = curNode
preNode.next = newNode
return listRef
def remove( listRef, target ):
assert listRef is not None, "No Node in the link list."
preNode = None
curNode = listRef
done = listRef is None
while not done:
preNode = curNode
curNode = curNode.next
if curNode.data == target:
if preNode is curNode:
listRef = None
return listRef
preNode.next = curNode.next
if curNode is listRef:
listRef = preNode
return listRef
else:
done = curNode is listRef or curNode.data > target
return listRef
if __name__ == '__main__':
#node_a = CListNode(1)
listRef = None
value = input('insert node( finished with -1): ')
while value != -1:
listRef = sortedInsert(listRef, value)
traverse( listRef )
value = input('insert node( finished with -1): ')
target = input('remove node( finished with -1): ')
while target != -1:
listRef = remove( listRef, target )
traverse( listRef )
target = input('remove node( finished with -1): ')