{"id":26780,"date":"2017-12-24T15:08:55","date_gmt":"2017-12-24T09:38:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26780"},"modified":"2017-12-24T15:08:55","modified_gmt":"2017-12-24T09:38:55","slug":"python-algorithm-introduction-stack","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-algorithm-introduction-stack\/","title":{"rendered":"Python Algorithm &#8211; Introduction to Stack"},"content":{"rendered":"<p>Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).<span id=\"more-2713\"><\/span><\/p>\n<p>Mainly the following three basic operations are performed in the stack:<\/p>\n<ul>\n<li><strong>Push: <\/strong>Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.<\/li>\n<li><strong>Pop:<\/strong> Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.<\/li>\n<li>Peek or Top: Returns top element of stack.<\/li>\n<li><strong>isEmpty: <\/strong>Returns true if stack is empty, else fals.<\/li>\n<li><strong>How to understand a stack practically?<\/strong><br \/>\nThere are many real life examples of stack. Consider the simple example of plates stacked over one another in canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO\/FILO order.<strong>Time Complexities of operations on stack:<\/strong>push(), pop(), esEmpty() and peek() all take O(1) time. We do not run any loop in any of these operations.<strong>Applications of stack:<\/strong><\/p>\n<ul>\n<li>Balancing of symbols<\/li>\n<li>Infix to Postfix \/Prefix conversion<\/li>\n<li>Redo-undo features at many places like editors, photoshop.<\/li>\n<li>Forward and backward feature in web browsers<\/li>\n<li>Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.<\/li>\n<li>Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver<\/li>\n<\/ul>\n<p><strong>Implementation:<\/strong><br \/>\nThere are two ways to implement a stack:<\/p>\n<ul>\n<li>Using array<\/li>\n<li>Using linked list<\/li>\n<\/ul>\n<p><strong>Implementing Stack using Arrays<\/strong><\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for implementation of stack<br\/> <br\/># import maxsize from sys module <br\/># Used to return -infinite when stack is empty<br\/>from sys import maxsize<br\/> <br\/># Function to create a stack. It initializes size of stack as 0<br\/>def createStack():<br\/>    stack = []<br\/>    return stack<br\/> <br\/># Stack is empty when stack size is 0<br\/>def isEmpty(stack):<br\/>    return len(stack) == 0<br\/> <br\/># Function to add an item to stack. It increases size by 1<br\/>def push(stack, item):<br\/>    stack.append(item)<br\/>    print(&quot;pushed to stack &quot; + item)<br\/>     <br\/># Function to remove an item from stack. It decreases size by 1<br\/>def pop(stack):<br\/>    if (isEmpty(stack)):<br\/>        return str(-maxsize -1) #return minus infinite<br\/>     <br\/>    return stack.pop()<br\/> <br\/># Driver program to test above functions    <br\/>stack = createStack()<br\/>push(stack, str(10))<br\/>push(stack, str(20))<br\/>push(stack, str(30))<br\/>print(pop(stack) + &quot; popped from stack&quot;)<\/code><\/pre> <\/div>\n<p><strong>Pros:<\/strong> Easy to implement. Memory is saved as pointers are not involved.<br \/>\n<strong>Cons:<\/strong> It is not dynamic. It doesn\u2019t grow and shrink depending on needs at runtime.<\/p>\n<p><strong>Output:<\/strong><\/p>\n<pre>10 pushed to stack\r\n20 pushed to stack\r\n30 pushed to stack\r\n30 popped from stack\r\nTop item is 20<\/pre>\n<p><strong>\u00a0 \u00a0 \u00a0 \u00a0Implementing Stack using Linked List<\/strong><\/p>\n<p><strong>Python Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for linked list implementation of stack<br\/> <br\/># Class to represent a node<br\/>class StackNode:<br\/> <br\/>    # Constructor to initialize a node<br\/>    def __init__(self, data):<br\/>        self.data = data <br\/>        self.next = None<br\/> <br\/>class Stack:<br\/>     <br\/>    # Constructor to initialize the root of linked list<br\/>    def __init__(self):<br\/>        self.root = None<br\/> <br\/>    def isEmpty(self):<br\/>        return True if self.root is None else  False<br\/> <br\/>    def push(self, data):<br\/>        newNode = StackNode(data)<br\/>        newNode.next = self.root <br\/>        self.root = newNode<br\/>        print &quot;%d pushed to stack&quot; %(data)<br\/>     <br\/>    def pop(self):<br\/>        if (self.isEmpty()):<br\/>            return float(&quot;-inf&quot;)<br\/>        temp = self.root <br\/>        self.root = self.root.next<br\/>        popped = temp.data<br\/>        return popped<br\/>     <br\/>    def peek(self):<br\/>        if self.isEmpty():<br\/>            return float(&quot;-inf&quot;)<br\/>        return self.root.data<br\/> <br\/># Driver program to test above class <br\/>stack = Stack()<br\/>stack.push(10)        <br\/>stack.push(20)<br\/>stack.push(30)<br\/> <br\/>print &quot;%d popped from stack&quot; %(stack.pop())<br\/>print &quot;Top element is %d &quot; %(stack.peek())<br\/> <br\/># This code is contributed by Nikhil Kumar Singh(nickzuck_007)<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>10 pushed to stack\r\n20 pushed to stack\r\n30 pushed to stack\r\n30 popped from stack\r\nTop element is 20<\/pre>\n<p><strong>Pros:<\/strong> The linked list implementation of stack can grow and shrink according to the needs at runtime.<br \/>\n<strong>Cons:<\/strong> Requires extra memory due to involvement of pointers.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Python Algorithm -Introduction to Stack &#8211; Data Structure -Stack is a linear data structure which follows a particular order in which the operations<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,4148,79607],"tags":[79873,79881,79879,79878,83685,79876,79877,79874,83687,79880,79875,79872,83686],"class_list":["post-26780","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-python","category-stack","tag-implement-queue-in-python","tag-inbuilt-stack-in-python","tag-python-list-peek","tag-python-stack-library","tag-python-stack-module","tag-python-stack-peek","tag-python-web-stack","tag-queues-in-python","tag-stack-implementation-using-linked-list-in-python","tag-stack-implementation-using-list-in-python","tag-stack-in-python-3","tag-stack-in-python-example","tag-stack-in-python-tutorial-point"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26780","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26780"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26780\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}