Stack Program in python with source code

 # Stack implementation in python



# Creating a stack

def create_stack():

    stack = []

    return stack



# Creating an empty stack

def check_empty(stack):

    return len(stack) == 0



# Adding items into the stack

def push(stack, item):

    stack.append(item)

    print("pushed item: " + item)



# Removing an element from the stack

def pop(stack):

    if (check_empty(stack)):

        return "stack is empty"


    return stack.pop()



stack = create_stack()

push(stack, str(1))

push(stack, str(2))

push(stack, str(3))

push(stack, str(4))

print("popped item: " + pop(stack))

print("stack after popping an element: " + str(stack))

Comments

  1. linked list
    class Node:
    def __init__(self, dataval=None):
    self.dataval = dataval
    self.nextval = None

    class SLinkedList:
    def __init__(self):
    self.headval = None

    def listprint(self):
    printval = self.headval
    while printval is not None:
    print (printval.dataval)
    printval = printval.nextval

    list = SLinkedList()
    list.headval = Node("Mon")
    e2 = Node("Tue")
    e3 = Node("Wed")

    # Link first Node to second node
    list.headval.nextval = e2

    # Link second Node to third node
    e2.nextval = e3

    list.listprint()

    ReplyDelete
  2. Insertion at end

    class Node:
    def __init__(self, dataval=None):
    self.dataval = dataval
    self.nextval = None
    class SLinkedList:
    def __init__(self):
    self.headval = None
    # Function to add newnode
    def AtEnd(self, newdata):
    NewNode = Node(newdata)
    if self.headval is None:
    self.headval = NewNode
    return
    laste = self.headval
    while(laste.nextval):
    laste = laste.nextval
    laste.nextval=NewNode
    # Print the linked list
    def listprint(self):
    printval = self.headval
    while printval is not None:
    print (printval.dataval)
    printval = printval.nextval

    list = SLinkedList()
    list.headval = Node("Mon")
    e2 = Node("Tue")
    e3 = Node("Wed")

    list.headval.nextval = e2
    e2.nextval = e3

    list.AtEnd("Thu")

    list.listprint()

    out put
    mon
    tue
    wed
    thu

    ReplyDelete

Post a Comment

Popular posts from this blog

गोभी का फूल(First Language Hindi Class X)With Paid Video Free