Stack implementation with Linked List using Swift

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).

Let's Code :


First make a simple Node class , with a data and  a pointer:

class Node {
    let nodeVal : Int
    var next : Node?
    init(value : Int) {
        self.nodeVal = value
    }

}

Now make the Stack Class, As we know Stack follows LIFO. We will implement  Push() and Pop() method within the class to Push and Pop elements.

class Stack {
    var top : Node?
    func push(_ value:Int){
        let oldTop = top
        top = Node(value: value)
        top?.next = oldTop
        print("Push Item to Stack : \(value)")
    }
    func pop() -> Int?{
        print("Popped Item from Stack : ")
        let currentTop = top
        top = top?.next
        return currentTop?.nodeVal
    }

}

Ok, so everything seems ready now, we can call them from anywhere :

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let stack = Stack()
        stack.push(1)
        stack.push(2)
        stack.push(3)
        
        print(stack.pop() ?? "Stack is Empty")
        print(stack.pop() ?? "Stack is Empty")
        print(stack.pop() ?? "Stack is Empty")
        print(stack.pop() ?? "Stack is Empty")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}



I just used an extra Pop() call, just to show that the Stack is Empty. So ...

Here is the output :


Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications