File tree Expand file tree Collapse file tree 4 files changed +51
-0
lines changed Expand file tree Collapse file tree 4 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -12,4 +12,11 @@ fun main() {
1212// singlyLinkedList.add("Awais")
1313// println(singlyLinkedList.copyToString())
1414
15+ println (" Hello, world!!!" )
16+
17+ val list: java.util.LinkedList <Int > = java.util.LinkedList <Int >()
18+
19+ list.add(0 )
20+ list.add(1 , 1 )
21+
1522}
Original file line number Diff line number Diff line change @@ -3,6 +3,7 @@ package kotlin_lang.lists
33interface Collection <T > {
44
55 fun add (element : T ): Boolean
6+ fun add (index : Int , element : T )
67
78
89}
Original file line number Diff line number Diff line change @@ -6,6 +6,7 @@ import kotlin_lang.lists.Collection
66class SinglyLinkedList <T > : Collection <T > {
77
88 var head: Node <T >? = null
9+ var sizeOfList: Int = 0
910
1011 override fun add (element : T ): Boolean {
1112 head?.let {
@@ -14,12 +15,23 @@ class SinglyLinkedList<T> : Collection<T> {
1415 currentNode = currentNode.nextRef!!
1516 }
1617 currentNode.nextRef = Node (element, null )
18+ sizeOfList++
1719 return true
1820 } ? : run {
1921 head = Node (element, null )
22+ sizeOfList++
2023 return true
2124 }
2225 }
2326
27+ override fun add (index : Int , element : T ) {
28+ if (index > sizeOfList) throw IndexOutOfBoundsException (" Index not accessible" )
29+
30+ head?.let {
31+ head = Node (element, null )
32+ }
33+
34+ }
35+
2436 data class Node <T >(var info : T , var nextRef : Node <T >? )
2537}
Original file line number Diff line number Diff line change 11package kotlin_lang.lists.singly_linked_list
22
33import org.junit.jupiter.api.Assertions.assertEquals
4+ import org.junit.jupiter.api.Assertions.assertThrows
45import org.junit.jupiter.api.BeforeEach
56import org.junit.jupiter.api.Test
67
@@ -37,5 +38,35 @@ class SinglyLinkedListTest {
3738 assertEquals(2 , linkedList.head?.nextRef?.nextRef?.info)
3839 }
3940
41+ @Test
42+ fun addByIndex_listIsEmpty_elementAddedToHead () {
43+ linkedList.add(0 , 0 )
44+ assertEquals(0 , linkedList.head?.info)
45+ }
46+
47+ @Test
48+ fun addByIndex_listIsEmpty_indexInRange_elementAddedToHead () {
49+
50+ linkedList.add(0 , 2 )
51+ assertEquals(2 , linkedList.head?.info)
52+ }
53+
54+ @Test
55+ fun addByIndex_listNotEmpty_indexInRange_elementAddedToHead () {
56+
57+ linkedList.add(0 , 1 )
58+ linkedList.add(1 , 2 )
59+ linkedList.add(2 , 3 )
60+ assertEquals(3 , linkedList.head?.nextRef?.nextRef?.info)
61+ }
62+
63+ @Test
64+ fun addByIndex_indexOutOfRange_throwsException () {
65+ assertThrows(IndexOutOfBoundsException ::class .java) {
66+ linkedList.add(4 , 1 )
67+ }
68+
69+ }
70+
4071
4172}
You can’t perform that action at this time.
0 commit comments