File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
com/williamfiset/algorithms/datastructures/linkedlist Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -77,6 +77,38 @@ 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
+ {
83
+ if (index <0 )
84
+ {
85
+ throw new Exception ("Illegal Index" );
86
+ }
87
+ if (index ==0 )
88
+ {
89
+ addFirst (data );
90
+ return ;
91
+ }
92
+
93
+ if (index ==size )
94
+ {
95
+ addLast (data );
96
+ return ;
97
+ }
98
+
99
+ Node <T > temp =head ;
100
+ for (int i =0 ;i <index -1 ;i ++)
101
+ {
102
+ head =head .next ;
103
+ }
104
+ Node <T > newNode = new Node (data ,null ,null );
105
+ newNode .next =head .next ;
106
+ newNode .prev =head .prev ;
107
+ head .next =newNode ;
108
+ head =temp ;
109
+
110
+ size ++;
111
+ }
80
112
// Check the value of the first node if it exists, O(1)
81
113
public T peekFirst () {
82
114
if (isEmpty ()) throw new RuntimeException ("Empty list" );
You can’t perform that action at this time.
0 commit comments