-
Notifications
You must be signed in to change notification settings - Fork 4
/
task1+2.py
102 lines (89 loc) · 3.07 KB
/
task1+2.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
class Node:
def __init__(self, data, next, prev):
self.data = data
self.next = next
self.prev = prev
class Doublylist:
def __init__(self, a):
self.head = Node(a[0], None, None)
tail = self.head
for x in range(1, len(a)):
new_node = Node(a[x], None, tail)
tail.next = new_node
tail = new_node
def showList(self):
if self.head.next is None:
print("Empty list")
else:
head = self.head
while self.head is not None:
if head.next is None:
print(head.data)
break
else:
print(head.data, "->", end=" ")
head = head.next
def insert(self, newElement):
head = self.head
new_node = Node(newElement, None, None)
while new_node.next is None:
if head.data == new_node.data:
print("key already exists and does not insert the key")
break
if head.next is None:
head.next = new_node
new_node.prev = head
break
head = head.next
def insert_index(self, newElement, index):
condition = False
if index == 0:
new_node = Node(newElement, self.head, None)
self.head.prev = new_node
self.head = new_node
else:
n = self.head
counter = 0
while n is not None:
n = n.next
if condition is False:
n = self.head
while n is not None:
counter = counter + 1
if n.data == newElement:
condition = True
print("key already exists and does not insert the key.")
if counter == index:
new_node = Node(newElement, n.next, n.prev)
n.next.prev = new_node
n.prev.next = new_node
n = n.next
def remove(self, index):
if self.head == None:
print("list is empty")
else:
counter = 0
head = self.head
while head is not None:
if index == counter:
head.next.prev = head.prev
head.prev.next = head.next
counter = counter+1
head = head.next
if index > counter:
print("index out of range")
def removeKey(self, key):
head = self.head
while head is not None:
if head.data == key:
head.next.prev = head.prev
head.prev.next = head.next
head = head.next
return key
a = [1, 2, 3, 4, 5]
mylist = Doublylist(a)
mylist.insert(6)
mylist.insert_index(8, 4)
# mylist.remove(2)
# mylist.removeKey(3)
mylist.showList()