-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyList.py
More file actions
89 lines (75 loc) · 1.87 KB
/
MyList.py
File metadata and controls
89 lines (75 loc) · 1.87 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
from ListNode import ListNode
class MyList:
def __init__(self):
self._count = 0
self._head = None
self._current = None
def add(self, newNode):
"""add an item into the list."""
if self._head == None:
self._head = newNode
self._current = self._head
else:
self._current._next = newNode
self._current = self._current._next
self._count += 1
def count(self):
"""return the item(s) number in this list"""
return self._count
def delete(self, position):
"""delete the n-th item (n = position)"""
if position < 0:
raise ValueError("wrong value.")
if position >= self._count:
raise OverflowError("position is too big.")
if position == 0:
temp = self._head._next
self._head._next = None
self._head = temp
self._count = 0
else:
temp = self._head
for x in xrange(1, position):
temp = temp._next
temp2 = temp._next
temp._next = temp2._next
temp2._next = None
self._count -= 1
def update(self, position, data):
"""update the n-th item (n = position)"""
if position < 0:
raise ValueError("wrong value.")
if position >= self._count:
raise OverflowError("position is too big.")
temp = self._head
for x in xrange(0, position):
temp = temp._next
temp._data = data
def get(self, position):
"""update the n-th item (n = position)"""
if position < 0:
raise ValueError("wrong value.")
if position >= self._count:
raise OverflowError("position is too big.")
temp = self._head
for x in xrange(0, position):
temp = temp._next
return temp._data
def showAll(self):
"""print all the item(s) in order."""
temp = self._head
while(temp != None):
print(temp._data)
temp = temp._next
def main():
list = MyList()
for x in xrange(1,10):
newNode = ListNode(x)
list.add(newNode)
list.update(3, 1000)
#list.delete(0)
#list.delete(3)
list.delete(8)
list.showAll()
print list.get(4)
main()