0% found this document useful (0 votes)
12 views

Python Codes A2

Uploaded by

mr bean
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)
12 views

Python Codes A2

Uploaded by

mr bean
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/ 3

PYTHON CODES A2

LINKED LISTS
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
def deleteNode(self, node, data):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place
instead.
"""
while node.val is not data:
node = node.next
node.val = node.next.val
node.next = node.next.next
head = make_list([1,3,5,7,9])
ob1 = Solution()
ob1.deleteNode(head, 3)
print_list(head)
PYTHON CODES A2
BINARY TREE
class TreeNode:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def Add(self, data):


if self.data:
if data < self.data:
if self.left is None:
self.left = TreeNode(data)
else:
self.left.Add(data)
elif data > self.data:
if self.right is None:
self.right = TreeNode(data)
else:
self.right.Add(data)
else:
self.data = data

def PrintTree(self):
if self.left:
self.left.PrintTree()
print(self.data)

if self.right:
self.right.PrintTree()

root = TreeNode(6)
root.Add(3)
root.Add(5)
root.Add(10)
root.Add(7)
root.PrintTree()
PYTHON CODES A2

QUEUE
queue = []

queue.append("Feroz")
queue.append("Shehran")
queue.append("Abid")

print("Initial queue")
print(queue)

# Removing elements from the queue


print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))

print("\nQueue after removing elements")


print(queue)

STACK
stack = []

stack.append("Feroz")
stack.append("Shehran")
stack.append("Abid")

print("Initial stack")
print(stack)

print("\nElements popped from stack:")


print(stack.pop())
print(stack.pop())

stack.append("Raj")

print("\nStack after elements are popped:")


print(stack)

You might also like