Skip to content

Commit 0d75a95

Browse files
authored
Merge pull request williamfiset#100 from Prashansa-K/patch-1
lgtm!
2 parents 9146442 + c815e8a commit 0d75a95

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

com/williamfiset/algorithms/datastructures/linkedlist/DoublyLinkedList.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,32 @@ public void addFirst(T elem) {
7777
size++;
7878
}
7979

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+
80106
// Check the value of the first node if it exists, O(1)
81107
public T peekFirst() {
82108
if (isEmpty()) throw new RuntimeException("Empty list");

javatests/com/williamfiset/algorithms/datastructures/linkedlist/LinkedListTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,20 @@ public void testAddLast() {
6262
list.addLast(5);
6363
assertEquals(list.size(), 2);
6464
}
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+
}
6579

6680
@Test
6781
public void testRemoveFirst() {

0 commit comments

Comments
 (0)