Skip to content

Commit 07ea3e8

Browse files
committed
circular linklist
1 parent b730188 commit 07ea3e8

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

myclinklist.py

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
class CListNode:
2+
def __init__( self, data ):
3+
self.data = data
4+
self.next = None
5+
6+
def traverse( listRef ):
7+
curNode = listRef
8+
done = listRef is None
9+
while not done:
10+
curNode = curNode.next
11+
print curNode.data,
12+
done = curNode is listRef
13+
print ''
14+
15+
def searchCircularList( listRef, target ):
16+
curNode = listRef
17+
done = listRef is None
18+
while not done:
19+
curNode = curNode.next
20+
if curNode.data == target:
21+
return True
22+
else:
23+
done = curNode is listRef or curNode.data > target
24+
return False
25+
26+
27+
def sortedInsert( listRef, value ):
28+
newNode = CListNode( value )
29+
if listRef is None: # empty list
30+
listRef = newNode
31+
newNode.next = newNode
32+
elif value < listRef.next.data: # insert in front
33+
newNode.next = listRef.next
34+
listRef.next = newNode
35+
elif value > listRef.data: # insert in back
36+
newNode.next = listRef.next
37+
listRef.next = newNode
38+
listRef = newNode
39+
else:
40+
preNode = None
41+
curNode = listRef
42+
done = listRef is None
43+
while not done:
44+
preNode = curNode
45+
curNode = curNode.next
46+
done = curNode is listRef or curNode.data > value
47+
newNode.next = curNode
48+
preNode.next = newNode
49+
return listRef
50+
51+
def remove( listRef, target ):
52+
assert listRef is not None, "No Node in the link list."
53+
preNode = None
54+
curNode = listRef
55+
done = listRef is None
56+
while not done:
57+
preNode = curNode
58+
curNode = curNode.next
59+
if curNode.data == target:
60+
if preNode is curNode:
61+
listRef = None
62+
return listRef
63+
preNode.next = curNode.next
64+
if curNode is listRef:
65+
listRef = preNode
66+
return listRef
67+
else:
68+
done = curNode is listRef or curNode.data > target
69+
return listRef
70+
71+
if __name__ == '__main__':
72+
#node_a = CListNode(1)
73+
listRef = None
74+
75+
value = input('insert node( finished with -1): ')
76+
while value != -1:
77+
listRef = sortedInsert(listRef, value)
78+
traverse( listRef )
79+
value = input('insert node( finished with -1): ')
80+
81+
82+
target = input('remove node( finished with -1): ')
83+
while target != -1:
84+
listRef = remove( listRef, target )
85+
traverse( listRef )
86+
target = input('remove node( finished with -1): ')
87+

0 commit comments

Comments
 (0)