Skip to content

Instantly share code, notes, and snippets.

@chriswebb09
Created May 11, 2017 19:49
Show Gist options
  • Save chriswebb09/d8da4cee8d5693a0d9fd79868bafe746 to your computer and use it in GitHub Desktop.
Save chriswebb09/d8da4cee8d5693a0d9fd79868bafe746 to your computer and use it in GitHub Desktop.
Linked Lists In Real World
import UIKit
class PlaylistItem {
var track: iTrack?
var next: PlaylistItem?
weak var previous: PlaylistItem?
}
extension PlaylistItem: Equatable {
static func ==(lhs: PlaylistItem, rhs: PlaylistItem) -> Bool {
return lhs.track!.previewUrl! == rhs.track!.previewUrl!
}
}
class LinkedList<T> {
public typealias Node = LLNode<T>
private var head: Node?
private var tail: Node?
var isEmpty: Bool {
return head == nil
}
var first: Node? {
return head
}
var last: Node? {
return tail
}
func append(value: T) {
let newNode = Node(value: value)
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
}
class LLNode<T> {
var value: T
var next: LLNode?
weak var previous: LLNode?
init(value: T) {
self.value = value
}
}
import UIKit
class Playlist {
private var head: PlaylistItem?
var itemCount: Int = 0
var isEmpty: Bool? {
return head == nil
}
private var last: PlaylistItem? {
if var track = head {
while case let next? = track.next {
track = next
}
return track
} else {
return nil
}
}
func append(newPlaylistItem: PlaylistItem?) {
itemCount += 1
if let lastItem = last {
newPlaylistItem?.previous = lastItem
lastItem.next = newPlaylistItem
} else if head == nil {
head = newPlaylistItem
}
}
func printAllKeys() {
var current: PlaylistItem! = head
var i = 1
while current != nil {
i += 1
current = current.next
}
}
func playlistItem(at index: Int) -> PlaylistItem? {
if index >= 0 {
var trackItem = head
var i = index
while let trackAt = trackItem, trackItem != nil {
if i == 0 {
return trackAt
}
i -= 1
trackItem = trackAt.next
}
}
return nil
}
func reverse() {
var track = head
while let currentTrack = track {
track = currentTrack.next
swap(&currentTrack.next, &currentTrack.previous)
head = currentTrack
}
}
func removeFromPlaylist(for playlistItem: PlaylistItem?) -> iTrack? {
let previous = playlistItem?.previous
let next = playlistItem?.next
if let previous = previous {
previous.next = next
} else {
head = next
}
next?.previous = previous
playlistItem?.previous = nil
playlistItem?.next = nil
guard let trackItem = playlistItem?.track else { return nil }
return trackItem
}
func removeAll() {
var track = head
while let next = track?.next {
track?.previous = nil
track = nil
track = next
}
}
func contains(playlistItem item: PlaylistItem) -> Bool {
guard let currentTrack = head else { return false }
while currentTrack != item && currentTrack.next != nil {
guard let currentTrack = currentTrack.next else { return false }
if currentTrack == item {
return true
}
}
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment