IMPLEMENTATION OF STACK

IMPLEMENTATION OF STACK

This is the implemenation of stack algorithm in data structures and algorithms in python programming language.

Stack Attributes and Methods: Before we implement our own stack class. lets review the properties and methods of a stackThe stack abstract data type is defined by the following structures and operations.A stack os structured, as described abobe, as an ordered collection of items where items are added to andremoved from the end called the "top". Stack are ordered a LIFO, The stack operatives are given below.

class stack
??? def __init__(self):
??????? self.items = []
??? # creates a new stack that is empty. it needs no parameters and returns an empty stack

??? def isEmpty(self):
??????? return self.items == []
??? # tests to see whether the stack is empty, it needs no parameters and returns a boolean value.

??? def push(self,item):
??????? self.items.append(item)
??? # adds a new item to the top of the stack. it needs no parameters and returns the item.

??? def pop(self):
??????? return self.item.pop()
??? # Removes the top item from the stack. it needs no parameters and returns the item. Stack is modified.

??? def peek(self):
??????? return self.items[len(self.items)-1]
??? # returns the top item from the stack but does not remove it. it needs no parameters. The stack is not modified.

??? def size(self):
??????? return len (self.items)
??? # returns the number of items on the stack. i needs no parameters and returns an integer.        

Below is the code implemenation:

# Below is the result of the above code.
s = stack(
print(s.isEmpty())

s.push(1)
s.push(2)
s.push(3)
s.peek()
s.size()
s.isEmpty()

s.pop()
s.pop()
s.size()
s.isEmpty())        

In Summary Stack is all about putting objects on each other. This approach is mostly seen in our web browsers. Just Take a moment to think of it, when you open a web page you have just implemented a stack algorithm, Now you open one page one after the other. This pages are all organised and put together in stack. If you want to go back all you need to do is close the last tab till the first one.

So guys this is my short article on stack pls make sure you share for your friends.


要查看或添加评论,请登录

Ebisintei Dennis的更多文章

社区洞察

其他会员也浏览了