Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Last active October 7, 2020 09:41
Show Gist options
  • Save alexpaul/9a42f02cdfecab341ce46520d9832748 to your computer and use it in GitHub Desktop.
Save alexpaul/9a42f02cdfecab341ce46520d9832748 to your computer and use it in GitHub Desktop.
Stack notes - incomplete implementation [MARKED FOR DELETION]
//
// main.swift
// Stack
//
// Created by Alex Paul on 10/6/20.
//
import Foundation
struct Stack<T> {
// private(set) public var allows access but not modification outside the LinkedList
private(set) public var elements = [T]()
}
// implement a stack using a linked list
// 1.
// create a node class that uses a double node
// ADT
// review: memory management, ARC, weak, strong, unowned
// [newObject retain]; // 1
// [newObject release]; // 0
// reference counting: is the OS managing the reference contains in the lifetime of an application
// init() - create objects
// deint() - called automatically when an object is destroyed
// - deint() won't get called if the object is in a retain cycle
class DLNode<T> {
// node has at minimum a value and a next pointer (references)
var value: T // no value exist
var next: DLNode<T>? // by default var is a strong reference
weak var previous: DLNode<T>?
init(_ value: T) { // 8
// ourValue = 8
self.value = value // 8
}
}
// node1 <-> node2 -> nil
// 2.
// create a linked list
// at minimun implement the following
// properties and functions
// count, isEmpty, peek
// append(), removeLast()
// extra: insert, replaceHead
// ADT
struct LinkedList<T> {
// data structure
private var head: DLNode<T>?
private var tail: DLNode<T>?
// could only get (retrieve) the value externally
// can mutate the value internally
private (set) public var count = 0
public var isEmpty: Bool {
return head == nil
}
// 1 -> 2 -> 3 -> nil
public var peek: T? {
return tail?.value
}
}
// 3.
// implement a stack using a linked list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment