-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchain.py
More file actions
90 lines (75 loc) · 2.28 KB
/
Copy pathchain.py
File metadata and controls
90 lines (75 loc) · 2.28 KB
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
88
89
90
class node(object):
def __init__(self, val, pnext=None, pprev=None):
self.val = val
self._next = pnext
# self._prev = pprev
def __repr__(self):
return str(self.val)
class Chain(object):
def __init__(self):
self.head = None
self.length = 0
def __repr__(self):
context = '<'
start = self.head
if not start:
return context + '>'
else:
context += str(self.head)
while start._next:
context += ', ' + str(start._next)
start = start._next
return context + '>'
def append(self, input_item):
item = None
if isinstance(input_item, node):
item = input_item
else:
item = node(input_item)
if not self.head:
self.head = item
self.length += 1
else:
start = self.head
while start._next:
start = start._next
start._next = item
self.length += 1
def getIndex(self, val):
start = self.head
index = 0
if self.length == 0:
raise ValueError('%s is not in chain' % str(val))
while start:
if start.val == val:
return index
start = start._next
index += 1
raise ValueError('%s is not in chain' % str(val))
def getVal(self, index):
if self.length <= index:
raise IndexError('chain index out of range')
start_index = 0
start = self.head
while start_index < index:
start_index += 1
start = start._next
return start.val
def remove(self, val):
start = self.head
prev_start = None
if self.length == 0:
raise ValueError('remove(%s): %s is not in chain' %
(str(val), str(val)))
while start:
if start.val == val:
if prev_start:
prev_start._next = start._next
else:
self.head = start._next
self.length -= 1
del start
return
prev_start = start
start = start._next
raise ValueError('%s is not in chain' % str(val))