-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathW5Q2.py
50 lines (46 loc) · 1.51 KB
/
W5Q2.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
class Node(object):
def __init__(self, value):
self.value=value
self.next=None
self.prev=None
class List(object):
def __init__(self):
self.head=None
self.tail=None
def insert(self,n,x):
#Not actually perfect: how do we prepend to an existing list?
if n!=None:
x.next=n.next
n.next=x
x.prev=n
if x.next!=None:
x.next.prev=x
if self.head==None:
self.head=self.tail=x
x.prev=x.next=None
elif self.tail==n:
self.tail=x
def delete(self,nvalue):
node = self.head
prevNode = None
while node != None:
if node.value == nvalue: #if node is one to delete
if prevNode != None: #to avoid error in removing first node do check
prevNode.next = node.next
else:
self.head = node.next
prevNode = node #changes value of prevNode each iteration
node = node.next #changes value of node each iteration
def display(self):
values=[]
n=self.head
while n!=None:
values.append(str(n.value))
n=n.next
print ("List: ",",".join(values))
if __name__ == '__main__':
l=List()
l.insert(None, Node(4))
l.insert(l.head,Node(6))
l.insert(l.head,Node(8))
l.display()