I successfully implemented a single linked list with a Display function that prints the list elements. I created an iterative reverse function but the list displayed is missing the last element and displaying None instead.
I went over my algorithm many times. Is there anything I am missing?
Thanks in advance.
class node(object):
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = node()
# append to list
def append(self, data):
new_node = node(data)
current = self.head # head of the list
while current.next != None: # while not last node
current = current.next # traverse
current.next = new_node # append
def display(self):
list = []
current = self.head
while current.next != None:
current = current.next
list.append(current.data)
print(list)
return
def reverse(self):
current = self.head
prev = None
while current:
next_ = current.next
current.next = prev
prev = current
current = next_
self.head = prev
Test Case:
list = LinkedList()
list.append(0)
list.append(1)
list.append(2)
list.append(3)
list.append(4)
list.display()
list.reverse()
list.display()
Output:
[0, 1, 2, 3, 4]
[3, 2, 1, 0, None]
The problem is that your linked list starts off with a blank head because of your constructors for node and linked list.
class node(object):
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = node()
If you notice when you create a new LinkedList object you will get a head that has no data in it, and you compensate in your print statement/appends by getting self.head.next first:
current = self.head # head of the list
while current.next != None: # while not last node
So that means when you set self.head in your reverse class at the very end you are setting the head to a non-blank head and you skip it in your print.
To compensate for this you need to create a new blank head and set next to prev:
def reverse(self):
current = self.head.next
prev = None
while current:
next_ = current.next
current.next = prev
prev = current
current = next_
#We create a new blank head and set the next to our valid list
newHead = node()
newHead.next = prev
self.head = newHead
Output is
[0, 1, 2, 3, 4]
[4, 3, 2, 1, 0]
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.