File tree Expand file tree Collapse file tree 2 files changed +40
-0
lines changed
com/williamfiset/algorithms/datastructures/linkedlist
javatests/com/williamfiset/algorithms/datastructures/linkedlist Expand file tree Collapse file tree 2 files changed +40
-0
lines changed Original file line number Diff line number Diff line change @@ -77,6 +77,32 @@ public void addFirst(T elem) {
77
77
size ++;
78
78
}
79
79
80
+ // Add an element at a specified index
81
+ public void addAt (int index , T data ) throws Exception {
82
+ if (index < 0 ) {
83
+ throw new Exception ("Illegal Index" );
84
+ }
85
+ if (index == 0 ) {
86
+ addFirst (data );
87
+ return ;
88
+ }
89
+
90
+ if (index == size ) {
91
+ addLast (data );
92
+ return ;
93
+ }
94
+
95
+ Node <T > temp = head ;
96
+ for (int i = 0 ; i < index - 1 ; i ++) {
97
+ temp = temp .next ;
98
+ }
99
+ Node <T > newNode = new Node (data , temp , temp .next );
100
+ temp .next .prev = newNode ;
101
+ temp .next = newNode ;
102
+
103
+ size ++;
104
+ }
105
+
80
106
// Check the value of the first node if it exists, O(1)
81
107
public T peekFirst () {
82
108
if (isEmpty ()) throw new RuntimeException ("Empty list" );
Original file line number Diff line number Diff line change @@ -62,6 +62,20 @@ public void testAddLast() {
62
62
list .addLast (5 );
63
63
assertEquals (list .size (), 2 );
64
64
}
65
+
66
+ @ Test
67
+ public void testAddAt () throws Exception {
68
+ list .addAt (0 , 1 );
69
+ assertEquals (list .size (), 1 );
70
+ list .addAt (1 , 2 );
71
+ assertEquals (list .size (), 2 );
72
+ list .addAt (1 , 3 );
73
+ assertEquals (list .size (), 3 );
74
+ list .addAt (2 , 4 );
75
+ assertEquals (list .size (), 4 );
76
+ list .addAt (1 , 8 );
77
+ assertEquals (list .size (), 5 );
78
+ }
65
79
66
80
@ Test
67
81
public void testRemoveFirst () {
You can’t perform that action at this time.
0 commit comments