Python Codes A2
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 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)
STACK
stack = []
stack.append("Feroz")
stack.append("Shehran")
stack.append("Abid")
print("Initial stack")
print(stack)
stack.append("Raj")