Skip to main content

Stacks

What is a Stack?
A Stack ADT is an ordered list in which insertion and deletion are done at the top end of the list.
A stack follows LIFO(Last In First Out) Principle i.e, the last element inserted is the first one to be deleted.

Why do we need Stack?
Well, in many algorithms you want to add objects to a temporary list at some point and then pull them off this list again at a later time. Often the order in which you add and remove these objects matters.

Applications of Stack
  • Balancing of symbols
  • Infix-to-Postfix conversion
  • Evaluation of postfix expression
  • Implementing function calls(Recursive)
  • Forward and Backward feature in a browser.
  • Redo & Undo sequence in a text editor.
  • Matching tags in HTML & XML.
  • Used in other algorithms like Tree traversal, Tower of Hanoi, Stock span, N Queens, etc.

Stack Operations
Main stack operations
Push: Inserts data onto stack
Pop: Removes and returns the last inserted element from the stack.

Auxiliary stack operations
Top: Returns the last element without removing it.
isEmpty: Indicates whether any elements are stored in a stack or not.
isFull: Indicates whether the stack is full or not.


Implementation
  • Array
  • Linked list
1. Stack using Array

public struct Stack<T> {
    
  /// Datastructure consisting of a generic item.
  fileprivate var array = [T]()

  /// The number of items in the stack.
  public var count: Int {
    return array.count
  }

  /// Verifies if the stack is empty.
  public var isEmpty: Bool {
    return array.isEmpty
  }

  /**
     Pushes an item to the top of the stack.
     
     - Parameter element: The item being pushed.
  */
  public mutating func push(_ element: T) {
    array.append(element)
  }

  /**
     Removes and returns the item at the top of the stack.
     
     - Returns: The item at the top of the stack.
  */
  public mutating func pop() -> T? {
    return array.popLast()
  }

  /// Returns the item at the top of the stack.
  public var top: T? {
    return array.last
  }
}
Space Complexity for n push operations O(n)
Time Complexity of Push() O(1)
Time Complexity of Pop() O(1)
Time Complexity of isEmpty() O(1)
Time Complexity of isFull() O(1)
Time Complexity of top() O(1) // Array.last = O(1)
Time Complexity of size()O(1) // Array.count = O(1)

2. Stack using LinkedList

public final class LinkedStack<T>{
    
    /// Linked List's Node Class De claration
    public class LinkedListNode<T> {
        var value: T
        var next: LinkedListNode?
        
        public init(value: T) {
            self.value = value
        }
    }
    
    /// Typealiasing the node class to increase readability of code
    public typealias Node = LinkedListNode<T>
    
    
    /// The head of the Linked List
    private(set) var head: Node?
    
    /// Computed property to iterate through the linked list and return the last node in the list (if any)
    public var top: T? {
        guard let node = head else {
            return nil
        }
        return node.value
    }
    
    /// Computed property to check if the linked list is empty
    public var isEmpty: Bool {
        return head == nil
    }
    
    /// Computed property to iterate through the linked list and return the total number of nodes
    public var count: Int {
        guard var node = head else {
            return 0
        }
        
        var count = 1
        while let next = node.next {
            node = next
            count += 1
        }
        return count
    }
    /// Append a value to the end of the list
    ///
    /// - Parameter value: The data value to be appended
    public func push(_ value: T) {
        let newNode = Node(value: value)
        newNode.next = head
        head = newNode
    }
    
    /// remove last element from the list and return it's value
    @discardableResult public func pop() -> T {
        precondition(!isEmpty)
        var current = head
        defer {
            current = nil
        }
        
        head = current?.next
        return current!.value
    }
    
    /// Function to remove all nodes/value from the list
    public func deleteStack() {
        head = nil
    }
}

Space Complexity for n push operationsO(n)
Time Complexity of Push() O(1)
Time Complexity of Pop() O(1)
Time Complexity of isEmpty() O(1)
Time Complexity of top()O(1)
Time Complexity of deleteStack() O(1)

Comments

Popular posts from this blog

UILabel text animation as in UIButton click

Animating UILabel textcolor is not easy as it seems, normal animation won't work on this property. The below code snippet animates the UILabel textcolor as in button click.
Change the duration and UIViewAnimationOptions to play with it. extensionUILabel{ func flashLabel() { func animate(duration:Double,alpha:CGFloat,completion:(()->())?){ UIView.transition(with: self, duration: duration, options: UIViewAnimationOptions.transitionCrossDissolve, animations: { self.textColor = self.textColor?.withAlphaComponent(alpha) }) { _ in completion?() } } animate(duration: 0.1, alpha: 0) { animate(duration: 0.3, alpha: 1, completion: nil) } } } Happy coding...

Confused OS Concepts

Difference between MultiProcessor and Multicore Processor? A multiprocessorsystem contains more than one CPU, allowing them to work in parallel.
multicoreCPU has multiple execution cores on one CPU so that multiple cores can work in parallel on separate operations at chip level. Difference between MultiProgramming, MultiTasking, MultiProcessing,      MultiThreading? MultiProgramming:To minimize the CPU Idle time, Multiprogramming was introduced in older days for single core processor. One or more programs are loaded into main memory which are ready to execute still, only one program is able to get the CPU for execution while all others are waiting for their turn. When currently running process is performing an I/O task, then OS may interrupt that process and give the control to another program(process context switching) loaded in main memory for execution and a running process keeps executing until either it voluntarily releases the CPU or when it blocks for an I/O operation.
With Mutil…

Stack Problem - Balancing of Symbols

Stack Problem - Balancing of Symbols
Problem: Given an expression string exp , write a program to examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.

Example:
Input: exp = “[()]{}{[()()]()}”
Output: Balanced Input: exp = “[(])”
Output: Not Balanced
Algorithm:
Create a stack.while ( end of input is not reached ) {If the character read is not a symbol to be balanced, ignore it.If the character is an opening delimiter like ( , {  or [ , PUSH it into the stack.If it is a closing symbol like ) , } , ] , then if the stack is empty report an error, otherwise POP the stack.If the symbol POP-ed is not the corresponding delimiter, report an error.At the end of the input, if the stack is not empty report an error.Implementation :
func balancingOfSymbols(string:String)->Bool{ guard string.count > 0else { return false } let symbols:[Character:Character] = ["{":"}","[":"]","(":")",] v…