Skip to content

Commit 291d1f7

Browse files
authored
addAt(index, data) function added
This function is intended to add a node of a specified data element to a particular index in the linked list.
1 parent dcf94d6 commit 291d1f7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,38 @@ 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+
{
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+
}
80112
// Check the value of the first node if it exists, O(1)
81113
public T peekFirst() {
82114
if (isEmpty()) throw new RuntimeException("Empty list");

0 commit comments

Comments
 (0)