Posts

Showing posts with the label Stack

Generic Stack implementation with Linked List using Swift

Image
Let's code : Create a generic Node class : class Node<T> {     let nodeVal : T     var next : Node ?     init (value : T ) {         self . nodeVal = value     } } Now, implement a Generic Stack class : class Stack<T> {     var top : Node < T >?     func push( _ value: T ){         let oldTop = top         top = Node (value: value)         top ?. next = oldTop         print ( "Push Item to Stack : \ ( value )" )     }     func pop() -> T ?{         print ( "Popped Item from Stack : " )         let currentTop = top         top = top ?. next         return currentTop?. nodeVal     } } Call from anywhere : imp...

Stack implementation with Linked List using Swift

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