Stack And Queue Implementation with LinkedList in Swift

I believe the best way to learn a language is to implement data structures. Below is my attempt to implement stack and queue in swift with generics.
Here are the reason why I used LinkedList and Generics.
- Generics helps us to use the data-structure with different data types as it is not tied to one data type.
- LinkedList implementation saves memory as compared to using array for stack implementation.
Queue Implementation with Generics
We start by implementing class Node
which has two properties value
and next
. Queue works on concept of first in first out (FIFO). Queue basically have two methods
1 Enqueue: This method add new nodes at the back of the list.
2. Dequeue: This method removes node from the beginning of the list.
class Node<T> { var value:T var next:Node? init(value:T) { self.value = value }}class Queue<T> { var tail:Node<T>? var head:Node<T>? var count:Int = 0 func dequeue () -> Node<T>? { if let node = head { head = head?.next count -= 1 return node } return nil } func enqueue(value:T) { let newNode = Node(value:value) if let tailNode = tail { tailNode.next = newNode newNode.next = nil tail = newNode } else { head = newNode tail = newNode } count += 1 }}
Stack Implementation with generics
We start by implementing class Node
which has two properties value
and next
. Stack works on concept of last in first out (LIFO). Stack basically have two methods
- Push: This method add new nodes at the back of the list.
- Pop: This method removes node from the back of the list.
class Node<T> { var value:T var next:Node? init(value:T) { self.value = value }}class Stack<T> { var head:Node<T>? func push(value:T){ let node = Node<T>(value: value) if let headNode = head { node.next = headNode head = node } else { head = node } } func pop() -> Node<T>? { if let headNode = head { let node = headNode head = headNode.next node.next = nil return node } return nil } func peek () -> Node<T>? { return head }}