-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.py
104 lines (72 loc) · 2.54 KB
/
linkedlist.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
"""
Start the program by hitting the F5 key. this brings up ine interactive intepreter
to insert a node at the begining, you type li.insertBegining("what i want to insert");
to insert at the end, you type li.insertEnd("what i want to insert");
to search, you type li.search("what i am searching for")
to display, you type li.display(), this displays nodes and the next node, that is what they are linked to
"""
class Node:
def __init__(self,initdata):
self.data = initdata
self.next = None;
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self,newnext):
self.next = newnext;
class LinkedList:
def __init__(self):
self.head = None;
self.tail = None;
"""
This method checks if list is empty and returns boolean
"""
def isEmpty(self):
return self.head == None;
def insertBegining(self,item):
temp = Node(item);
temp.setNext(self.head);
#if list is empty, set tail to node
if self.isEmpty() == True:
self.tail = temp;
self.head = temp;
def insertEnd(self,item):
temp = Node(item);
if self.isEmpty() != True:
self.tail.setNext(temp);
self.tail = temp;
def search(self,item):
current = self.head;
found = False;
while current != None and not found:
if current.getData() == item:
found = True;
else:
current = current.getNext();
return found;
def display(self):
current = self.head;
while current != None:
print(current.getData());
print("------------>"+current.getNext().getData()) if current.getNext() != None else print("---------->None");
current = current.getNext();
#This can be skipped as it is not part of the assignment. this is used for deleting nodes from the list
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__":
li = LinkedList();