I have made a Node and Deque class to represent a double linked list. I wrote a function to return the first item in the linked list, but was getting an IndexError - an error that I have raised in my code in case the linked list is empty.
My expected output:
my_list.push_front(1)
my_list.push_front(2)
my_list.push_front(3)
linked list is [3, 2, 1]
print(my_list.peek_front()) --> 3
My linked list function file:
class Node:
"""
Initialize empty node
"""
def __init__(self, data=None, prev = None, next = None):
self.data = data
self.next = next
self.prev = prev
class Deque:
"""
A double-ended queue
"""
def __init__(self):
"""
Initializes an empty Deque
"""
self.head = Node()
def push_front(self, e): #should work fine
"""
Inserts an element at the front of the Deque
:param e: An element to insert
"""
new_head = Node(data = e, next = self.head)
if self.head:
self.head.prev = new_head
self.head = new_head
def peek_front(self): #FUNCTION WITH ERROR
"""
Looks at, but does not remove, the first element
:return: The first element
"""
if self.head.data == None: #if it is empty, raise error
raise IndexError
else:
return self.head.data
def listprint(self, node):
"""
Prints each element of the node front to back
:param node:
"""
while (node is not None):
print(node.data)
last = node
node = node.next
My main file:
def main():
my_list = Deque()
my_list.push_front(1)
my_list.push_front(2)
my_list.push_front(3)
my_list.listprint(my_list.head) #print elements in the list
print(my_list.peek_front())
My error message:
IndexError (error that was unintentionally raised by me)
Not getting your error (and I tried on python2 and python3, though out of laziness I just ran it as scripts without def main()
).
However, the output lists a None
at the end of the listprint:
$ python test.py
3
2
1
None
3
This is because what your __init__
creates is not an empty deque but rather a deque with a single node that has empty data. Maybe that's your way of implementing an empty deque (not a good idea if you ask me), but then you shouldn't be surprised that this empty-data node persists as you add new stuff onto the deque (after all, you never remove it).
If you want to fix this behavior, replace self.head = Node()
by self.head = None
in the __init__
, and replace if self.head.data == None
by if self.head is None
in the peek_front
(note: is None
is better Python than == None
, since the identity check is enough and the equality check involves indirection). I think the rest should work, but I haven't checked.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.