Created
June 14, 2017 14:24
-
-
Save prydt/088b866aa8e46469aa7bbb44f675fa08 to your computer and use it in GitHub Desktop.
A basic Singly 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
package prydt.source // just a package, m8 | |
/** | |
* Created by PryDt on 6/13/2017. | |
*/ | |
// basic node on list | |
data class Node<T>(var key: T?, var next: Node<T>?) | |
// the list class | |
class SinglyLinkedList<T> | |
{ | |
// the start of the list | |
var root = Node<T>(null, null) | |
// the length of the list | |
var length = 0 | |
// add a node to the end of the list | |
fun push(key: T){ | |
var node = Node(key, null) | |
var ptr = root | |
if(ptr.equals(Node<T>(null, null))) | |
{ | |
ptr.key = key | |
length++ | |
return | |
} | |
while(ptr.next != null) | |
ptr = ptr.next!! | |
ptr.next = node | |
length++ | |
} | |
// checking whether a certain value is in the list | |
fun search(key: T): Boolean { | |
var ptr = root | |
while(ptr.key != key && ptr.next != null) | |
ptr = ptr.next!! | |
return (ptr.key == key) | |
} | |
// returns the length of the list | |
inline fun size() = length | |
// prints out list to stdout | |
fun printList() { | |
print("[ ") | |
var ptr = root | |
while(ptr.next != null) | |
{ | |
print("${ptr.key} -> ") | |
try { | |
ptr = ptr.next!! | |
}catch (e: Exception) | |
{ | |
} | |
} | |
println("null ]") | |
println("Length of List: ${size()}, null doesn't count") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment