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.

  1. Generics helps us to use the data-structure with different data types as it is not tied to one data type.
  2. 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
  }
}

#linked-list-with-generics #swift #stack #data-structures #queue #data analysis

Stack And Queue Implementation with LinkedList in Swift
1.70 GEEK