Append and Traverse a Doubly Linked List using Swift - iOS
Let's Code :
OK, let's see the result first , Adding some random city names to linked list and printing the linked list :
Let's create the node now :
Node.swift
Now implement linked list in another swift file
DoublyLinkedList. swift
OK, let's see the result first , Adding some random city names to linked list and printing the linked list :
Let's create the node now :
Node.swift
import Foundation
class Node: NSObject {
var next: Node?
weak var previous: Node?
var value : String?
init(value : String) {
self.value = value
}
}
Now implement linked list in another swift file
DoublyLinkedList. swift
import UIKit
class DoublyLinkedList: NSObject {
fileprivate var head : Node?
private var tail : Node?
override init() {
super.init()
}
public var isEmpty : Bool {
return head == nil
}
public var first : Node? {
return head
}
public var last : Node? {
return tail
}
func append(str : String) {
let newNode = Node(value: str)
if let tailNode = tail {
tailNode.next = newNode
newNode.previous = tailNode
}
else{
head = newNode
}
tail = newNode
print("Added new Node to Linked List : [ \(str) ]")
}
func printDoublyLiskedList() {
var node = self.first
print("\nPrinting Doubly Linked List : ")
while node != nil {
let nodeValue : String = node!.value!
print("\(nodeValue)")
node = node?.next
}
}
}
Use the linked list where you want - just showing an example below
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let doublyLL = DoublyLinkedList()
doublyLL.append(str: "Kolkata")
doublyLL.append(str: "Hyderabad")
doublyLL.append(str: "Pune")
doublyLL.printDoublyLiskedList()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}

Comments
Post a Comment