Skip to content

Instantly share code, notes, and snippets.

@sergenes
Created October 11, 2018 00:37
Show Gist options
  • Save sergenes/3a13f335b50f5f84bac7ac932edb4bfa to your computer and use it in GitHub Desktop.
Save sergenes/3a13f335b50f5f84bac7ac932edb4bfa to your computer and use it in GitHub Desktop.
class Node<T>(var data: T, var nextNode: Node<T>? = null)
class LinkedList<T> {
var size: Int = 0
var head: Node<T>? = null
//O(1)
fun insertStart(data: T) {
size += 1
val newNode = Node(data = data)
head?.let {
newNode.nextNode = head
head = newNode
} ?: run {
head = newNode
}
}
//O(n)
fun insertEnd(data: T) {
size += 1
val newNode = Node(data = data)
var actualNode = head
while (actualNode?.nextNode != null) {
actualNode = actualNode.nextNode
}
actualNode!!.nextNode = newNode
}
//O(n)
fun remove(data:T){
if (head == null){
return
}
size -=1
var currentNode = head
var prevNode:Node<T>? = null
while (currentNode?.data != data){
prevNode = currentNode
currentNode = currentNode?.nextNode
}
if (prevNode == null){
head = currentNode!!.nextNode
}else{
prevNode.nextNode = currentNode!!.nextNode
}
}
//O(1)
fun size(): Int {
return size
}
//O(n)
fun size2(): Int {
var actualNode = head
var size = 0
while (actualNode != null) {
size += 1
actualNode = actualNode.nextNode
}
return size
}
fun traverseList() {
var actualNode = head
while (actualNode?.nextNode != null) {
println("${actualNode.data}")
actualNode = actualNode.nextNode
}
println("${actualNode?.data}")
}
}
fun main(args: Array<String>) {
val list = LinkedList<Int>()
val listStr = LinkedList<String>()
listStr.insertStart("1")
listStr.insertStart("12")
listStr.insertStart("31")
listStr.insertStart("44")
listStr.traverseList()
list.insertStart(12)
list.insertStart(122)
list.insertStart(3)
list.insertEnd(31)
list.insertEnd(32)
list.traverseList()
println("size=>${list.size()}")
list.remove(12)
list.remove(3)
list.remove(122)
list.remove(31)
list.remove(32)
println("size=>${list.size()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment