-
Notifications
You must be signed in to change notification settings - Fork 595
/
P33_DoublyLinkedList.py
108 lines (90 loc) · 2.83 KB
/
P33_DoublyLinkedList.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
103
104
105
106
107
108
#Author: OMKAR PATHAK
#This program illustrates an example of singly linked list
class Node(object):
def __init__(self, data, Next = None, Previous = None):
self.data = data
self.next = Next
self.previous = Previous
def getNext(self):
return self.next
def getPrevious(self):
return self.previous
def getData(self):
return self.data
def setData(self, newData):
self.data = newData
def setNext(self, newNext):
self.next = newNext
def setPrevious(self, newPrevious):
self.previous = newPrevious
class LinkedList(object):
def __init__(self):
self.head = None
def isEmpty(self):
''' This function checks whether the list is empty'''
return self.head == None
def insertFirst(self, data):
''' This function inserts a new node in the Linked List '''
newNode = Node(data)
if self.head:
self.head.setPrevious(newNode)
newNode.setNext(self.head)
self.head = newNode
def insertLast(self, data):
newNode = Node(data)
current = self.head
while current.getNext() != None:
current = current.getNext()
current.setNext(newNode)
newNode.setPrevious(current)
# def insertBetween(self, newItem, item):
# current = self.head
# newNode = Node(newItem)
# previous = None
# found = False
# while not found:
# if current.getData() == item:
# found = True
# else:
# previous = current
# current = current.getNext()
#
# if previous == None:
# self.head = current.getPrevious()
# else:
# previous.setNext(newNode)
# newNode.setPrevious(previous)
def getAllData(self):
''' This function displays the data elements of the Linked List '''
current = self.head
elements = []
while current:
elements.append(current.getData())
current = current.getNext()
return elements
def remove(self,item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext())
if __name__ == '__main__':
myList = LinkedList()
myList.insertFirst(1)
myList.insertFirst(12)
myList.insertFirst(32)
myList.insertFirst(22)
myList.insertLast(2)
myList.remove(12)
# myList.insertBetween(12, 22)
# for i in range(0, 10):
# myList.insertFirst(i)
print(myList.getAllData())