File tree Expand file tree Collapse file tree 1 file changed +25
-12
lines changed
src/me/ramswaroop/linkedlists Expand file tree Collapse file tree 1 file changed +25
-12
lines changed Original file line number Diff line number Diff line change @@ -34,16 +34,10 @@ public boolean add(E item) {
34
34
35
35
@ Override
36
36
public boolean add (int index , E item ) {
37
- // base case
38
- if (index > size ) {
39
- throw new IndexOutOfBoundsException ("LinkedList isn't long enough." );
40
- }
41
- // linkedlist is empty
42
- if (head == null ) {
43
- head = new Node <>(item , null );
44
- } else if (index == 0 ) { // add at first
45
- Node <E > newNode = new Node <>(item , head );
46
- head = newNode ;
37
+ isIndexOutOfBounds (index );
38
+
39
+ if (index == 0 ) { // add at first
40
+ addFirst (item );
47
41
} else { // add at any other location
48
42
Node <E > curr = head ;
49
43
int i = 0 ;
@@ -60,12 +54,13 @@ public boolean add(int index, E item) {
60
54
61
55
@ Override
62
56
public void addFirst (E item ) {
63
-
57
+ Node <E > newNode = new Node <>(item , head );
58
+ head = newNode ;
64
59
}
65
60
66
61
@ Override
67
62
public void addLast (E item ) {
68
-
63
+ add ( item );
69
64
}
70
65
71
66
@ Override
@@ -140,6 +135,24 @@ public void printList() {
140
135
out .println (curr .item + "]" );
141
136
}
142
137
138
+ private Node <E > getNode (int index ) {
139
+ isIndexOutOfBounds (index );
140
+
141
+ Node <E > curr = head ;
142
+ int i = 0 ;
143
+ while (i < index - 1 ) {
144
+ curr = curr .next ;
145
+ i ++;
146
+ }
147
+ return curr ;
148
+ }
149
+
150
+ private void isIndexOutOfBounds (int index ) {
151
+ if (index < 0 && index > size ) {
152
+ throw new IndexOutOfBoundsException ("Index must be less than or equal to: " + size );
153
+ }
154
+ }
155
+
143
156
private class Node <E > {
144
157
E item ;
145
158
Node <E > next ;
You can’t perform that action at this time.
0 commit comments