-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list.py
110 lines (83 loc) · 2.52 KB
/
linked_list.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
109
110
class Link(object):
''' This class represents a link between data items only'''
def __init__ (self, data, next = None):
self.data = data
self.next = next
def __str__(self):
return str(self.data) + " --> " + str(self.next)
class LinkedList(object):
''' This class implements the operations of a simple linked list'''
def __init__ (self):
self.first = None
def insertFirst (self, data):
'''inset data at begining of a linked list'''
newLink = Link(data)
newLink.next = self.first
self.first = newLink
def insertLast (self, data):
''' Inset the data at the end of a linked list '''
newLink = Link(data)
current = self.first
if (current == None):
self.first = newLink
return
# find the last and insert it there.
while (current.next != None):
current = current.next
current.next = newLink
def findLink(self, data):
''' find to which data is the link of a given data inside this linked list'''
current = self.first
if (current == None):
return None
# searcg and find the position of the given data, the get the link if.
while (current.data != data):
if (current.next == None):
return None
else:
current = current.next
return current
def deleteLink(self, data):
''' Removes the data from the list if exist and fix the link problems.'''
current = self.first
previous = self.first
if (current == None):
return None
while (current.data != data):
if (current.next == None):
return None
else:
previous = current
current = current.next
if (current == self.first):
self.first = self.first.next
else:
previous.next = current.next
return current
def __str__(self):
return str(self.first)
class Stack (object):
def __init__(self):
self.linked_head = LinkedList()
def push(self, item):
if self.linked_head == None:
self.linked_head = Link(item)
else:
self.linked_head.insertFirst()
def pop(self):
if self.linked_head == None:
return None
else:
return self.linked_head.deleteLink()
def peek(self):
if self.linked_head == None:
return None
else:
return self.linked_head.data
def isEmpty (self):
if self.linked_head == None:
return True
else:
return False
def __str__(self):
return str(self.linked_head)