In: Computer Science
PYTHON-- how do i change these linkedlist methods into doublylinkedlist methods? A doublylinked list is the same as a linked list, except that each node has a reference to the node after it(next) and the node before it(prev). #adds item to the head of list. def add(self, item): node = Node(item, self.head) self.head = node if self.size == 0: self.tail = node self.size += 1
#appends item to tail of list def append(self, item): node = Node(item) tail = self.head node.next = None if self.size == 0: node.prev = None self.head = node return while tail.next is not None: tail = tail.next tail.next = node node.prev = tail self.size += 1 #removes the node at position pos. returns node's data #make pop O(1)
def pop(self, pos=None): current = self.head previous = None i = 0 while current != None and i != pos: previous = current current = current.next i += 1
if current == self.tail: previous.next = None self.tail = previous self.size -= 1 return current.data elif prev is None: if self.size == 1: self.tail = None self.head = current.next self.size -= 1 return current.data else: previous.next = current.next self.size -= 1 return current.data
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU
class Node:
def __init__(self, item):
self.item = item
self.next = None
self.prev = None
class DoubleLinkedList:
def __init__(self):
self.dllnode = None
# adds item to the head of list
def add(self, item):
if(self.dllnode == None):
new_node = Node(item)
self.dllnode = new_node
new_node = Node(item)
new_node.next = self.dllnode
self.dllnode.prev = new_node
self.dllnode = new_node
# adds item to the end of list
def append(self, item):
new_node = Node(item)
new_node.next = None
if self.dllnode is None:
new_node.prev = None
self.dllnode = new_node
return
temp = self.dllnode
if temp.next is not None:
temp = temp.next
temp.next = new_node
new_node.prev = temp
# print list
def printList(self):
while(self.dllnode is not None):
print(self.dllnode.item, end="->")
self.dllnode = self.dllnode.next
# removes the node at position pos return node data
def pop(self, pos):
if(self.dllnode is None):
return
cur = self.dllnode
i = 1
while(cur != None and i != pos):
cur = cur.next
i = i+1
if(cur == None):
return
# node to be deleted
if(self.dllnode == None or cur == None):
return
# if the node is the first or head node
if(self.dllnode == cur):
self.dllnode = cur.next
# if the node is the last node
if(cur.next is not None):
cur.next.prev = cur.prev
if(cur.prev is not None):
cur.prev.next = cur.next
return self.dllnode.item
node = DoubleLinkedList()
node.add(20)
node.add(30)
node.append(50)
print(node.pop(2))
print(node.printList())