Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 325ce5e

Browse files
author
Ram swaroop
committed
linkedlist: addfirst and addlast done
1 parent 5ba5180 commit 325ce5e

File tree

1 file changed

+25
-12
lines changed

1 file changed

+25
-12
lines changed

src/me/ramswaroop/linkedlists/SingleLinkedList.java

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,10 @@ public boolean add(E item) {
3434

3535
@Override
3636
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);
4741
} else { // add at any other location
4842
Node<E> curr = head;
4943
int i = 0;
@@ -60,12 +54,13 @@ public boolean add(int index, E item) {
6054

6155
@Override
6256
public void addFirst(E item) {
63-
57+
Node<E> newNode = new Node<>(item, head);
58+
head = newNode;
6459
}
6560

6661
@Override
6762
public void addLast(E item) {
68-
63+
add(item);
6964
}
7065

7166
@Override
@@ -140,6 +135,24 @@ public void printList() {
140135
out.println(curr.item + "]");
141136
}
142137

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+
143156
private class Node<E> {
144157
E item;
145158
Node<E> next;

0 commit comments

Comments
 (0)