0% found this document useful (0 votes)
43 views1 page

Dsa (Midterm)

The document describes operations performed on a linked list: 1) Nodes with data 1, 23, and 6 are inserted at the start, 23 is then removed. 2) A node with data 4 is inserted after the node with data 1. 3) A node with data 6 is inserted at the end.

Uploaded by

Geramier Apostol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views1 page

Dsa (Midterm)

The document describes operations performed on a linked list: 1) Nodes with data 1, 23, and 6 are inserted at the start, 23 is then removed. 2) A node with data 4 is inserted after the node with data 1. 3) A node with data 6 is inserted at the end.

Uploaded by

Geramier Apostol
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Insert_after(5,1) Head → none

Insert_start(1) Head → 1 → none


Insert_start(23) Head → 23 → 1 → none
Insert_after(4,1 )Head → 23 → 1 → none
Insert_end(6) Head → 23 → 1 → 6 → none
Remove(23) Head → 1 → 6 → none

class Node: 1
2
def __init__(self,data):
def add_after(self, target_node_data, new_node):
self.data = data
if self.head is None:
self.next = None
raise Exception("List is Empty")
def __repr__(self):
return self.data
# To Search
for node in self:
class LinkedList:
if node.data == target_node_data:
new_node.next = node.next
# To Remove
node.next = new_node
def remove(self,removekey):
return # STOP THE METHOD
node = self.head
raise Exception("Node with data '%s' not found" %
if (node is not None):
target_node_data)
if (node.data == removekey):
self.head = node.next
# Function for Traversal
node = None
def __iter__(self):
return
node = self.head
while node is not None:
while (node is not None):
yield node
if node.data == removekey:
node = node.next
break
prev = node
# END FUNCTION
node = node.next
def add_first(self, node):
if (node == None):
node.next = self.head
return
self.head = node
prev.next = node.next
node = None
def add_last(self, node): 3
if self.head is None:
def add_after(self, target_node_data, new_node): self.head = node
if self.head is None: return
raise Exception("List is Empty") for current_node in self:
pass
current_node.next = node

def __init__(self):
self.head = None

def __repr__(self):
node = self.head
nodes = []
while node is not None:
nodes.append(node.data)
node = node.next
nodes.append("None")
return " -> ".join(nodes)

LL = LinkedList()

LL.add_last(Node("3"))
LL.add_last(Node("5"))
LL.add_last(Node("5"))
LL.add_last(Node("3"))
LL.add_last(Node("3"))
LL.add_last(Node("1"))
LL.remove("3")

print(LL)

You might also like