Last active
October 8, 2020 20:10
-
-
Save SandeepAggarwal/2305e55c3efcfc9bafe68625523e8f8d to your computer and use it in GitHub Desktop.
Delete a node in a linked list whose head is not given
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import PlaygroundSupport | |
class Node { | |
var data: Int | |
var next: Node? | |
init(data: Int) { | |
self.data = data | |
} | |
} | |
class LinkedList { | |
var head: Node? | |
init(head: Node?) { | |
self.head = head | |
} | |
func printList() { | |
print("list is: ") | |
var node: Node? = head | |
while let current = node { | |
print(current.data) | |
node = current.next | |
} | |
} | |
func delete(node: Node) { | |
node.data = node.next?.data ?? -1 | |
node.next = node.next?.next | |
} | |
} | |
let node2 = Node(data: 2) | |
let node4 = Node(data: 4) | |
let node7 = Node(data: 7) | |
let node10 = Node(data: 10) | |
node2.next = node4 | |
node4.next = node7 | |
node7.next = node10 | |
let ll2 = LinkedList(head: node2) | |
ll2.printList() | |
ll2.delete(node: node4) | |
ll2.printList() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment