Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding examples on Swift. #16

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions Swift/Double.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import Foundation

class Node {
var data: String

var next: Node?
weak var previous: Node? // weak to avoid memory leak. ARC do the trick.
// Every Node knows only its neighbours
init(with data: String) {
self.data = data
}
}

class LinkedList {
private var head: Node?
private var tail: Node? // List knows its head and tail.

var isEmpty: Bool {
return head == nil
}

var first: Node? {
return head
}

var last: Node? {
return tail
}

func append(value: String) {
let newNode = Node(with: value)

if let tailNode = tail { // if tail exist
newNode.previous = tailNode
tailNode.next = newNode
}
else {
head = newNode // This is the first append
}
tail = newNode
}

func printList() {
var text = "["
var node = head

while node != nil {
text += "\(node!.data)"
node = node!.next
if node != nil { text += ", " }
}
text += "]"
print(text)
}


func removeAll() { // When head and tail is nil, weak ref will automatically delete its references one by one.
head = nil
tail = nil
}


func node(at index: Int) -> Node? {
if index >= 0 {
var node = head
var i = index

while node != nil {
if i == 0 { return node } // Iterating over the List
i -= 1
node = node!.next
}
}
return nil
}

}


let myList = LinkedList()

myList.append(value: "1231")
myList.append(value: "Car")
myList.append(value: "Dog")
myList.append(value: "Harry Potter")

myList.printList() // [1231, Car, Dog, Harry Potter]
let secondNode = myList.node(at: 1)?.data // Car

myList.removeAll()

myList.printList() // []
4 changes: 4 additions & 0 deletions Swift/Double.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.