Skip to content

Commit 4feeed8

Browse files
authored
Update DoublyLinkedList.java
1 parent 291d1f7 commit 4feeed8

File tree

1 file changed

+26
-31
lines changed

1 file changed

+26
-31
lines changed

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

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -78,37 +78,32 @@ public void addFirst(T elem) {
7878
}
7979

8080
// 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-
}
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, null, null);
100+
newNode.next = temp.next;
101+
newNode.prev = temp.prev;
102+
temp.next = newNode;
103+
104+
size++;
105+
}
106+
112107
// Check the value of the first node if it exists, O(1)
113108
public T peekFirst() {
114109
if (isEmpty()) throw new RuntimeException("Empty list");

0 commit comments

Comments
 (0)