Created
January 6, 2020 20:26
-
-
Save dicarlomagnus/11235207e7ca0b27e6e7945a0b46b6c5 to your computer and use it in GitHub Desktop.
Linked List in kotlin
This file contains 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 java.lang.StringBuilder | |
fun main() { //testing Linked List | |
var linkedList = LinkedList() | |
println(linkedList) | |
linkedList.preAppend(1).preAppend(2).preAppend(3) | |
println(linkedList) | |
linkedList.clear() | |
linkedList.append(1).append(2).append(3) | |
println(linkedList) | |
linkedList.deleteWithValue(2) | |
println(linkedList) | |
linkedList.deleteWithValue(3) | |
println(linkedList) | |
linkedList.deleteWithValue(2) | |
println(linkedList) | |
linkedList.deleteWithValue(1) | |
println(linkedList) | |
} | |
class Node(var data: Int) { | |
var next: Node? = null | |
} | |
class LinkedList { | |
private var head: Node? = null | |
fun append(data: Int): LinkedList { | |
if (head == null) { | |
head = Node(data) | |
return this | |
} | |
var current = head | |
while (current?.next != null) { | |
current = current?.next | |
} | |
current?.next = Node(data) | |
return this | |
} | |
fun preAppend(data: Int): LinkedList { | |
var newHead = Node(data) | |
newHead.next = head | |
head = newHead | |
return this | |
} | |
fun clear() { | |
head = null | |
} | |
fun deleteWithValue(data: Int): LinkedList { | |
if (head?.data == data) { | |
head = head?.next | |
return this | |
} | |
var current = head | |
while (current?.next != null) { | |
if (current?.next?.data == data) { | |
return if (current?.next?.next != null) { | |
current?.next = current?.next?.next | |
this | |
} else { | |
current.next = null | |
this | |
} | |
current = current?.next | |
} | |
} | |
return this | |
} | |
override fun toString(): String { | |
var string: StringBuilder = StringBuilder("{ ") | |
if (head == null) { | |
string.append("empty Linked List ") | |
} else { | |
var current = head | |
do { | |
string.append("${current?.data} ") | |
current = current?.next | |
} while ((current != null)) | |
} | |
return string.append("}").toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment