Singly and Doubly Linked List have the following methods: Insertion: insertAt, i
ID: 3871697 • Letter: S
Question
Singly and Doubly Linked List have the following methods:
Insertion: insertAt, insertAtFront, and insertAtEnd
Deletion: removeAt, removeAtFront, and removeAtEnd
InsertAtFront and removeAtFront calls insertAt and removeAt by passing 0 as an index respectively. Moreover, insertAtEnd and removeAtEnd calls insertAt and removeAt by passing size (number of elements in Linked List) as an index respectively.
Write insertAt and removeAt JAVA methods (one for Singly and one for Doubly Linked List) that inserts and removes an elements from the List by index.
Explanation / Answer
Singly Linked list
// Insert at
Node insertAt(Node head, int data, int index) {
Node temp = new Node();
temp.next = head;
Node temp2 = temp;
for (int i = 0; i < index; ++i) {
temp2 = temp2.next;
}
Node node = new Node();
node.data = data;
node.next = temp2.next;
temp2.next = node;
return temp.next;
}
// Remove at
void removeAt(int index)
{
// check If list is empty
if (head == null)
return;
Node temp = head;
if (index == 0)
{
head = temp.next;
return;
}
for (int i=0; temp!=null && i<index-1; i++)
temp = temp.next;
if (temp == null || temp.next == null)
return;
Node next = temp.next.next;
temp.next = next;
}
Doubly Linked Lst
/ insert element at index /
public void insertAt (int data , int index)
{
Node nptr = new Node(data, null, null);
Node temp = head;
for (int i = 2; i <= size; i++)
{
if (i == index)
{
Node tmp = temp.next;
temp.next=nptr;
nptr.prev = temp;
nptr.next=tmp;
tmp.prev =nptr;
}
temp = temp.next;
}
size++ ;
}
/ Function to delete node at position /
public void deleteAt (int index)
{
if (index == 1)
{
if (size == 1)
{
head = null;
tail = null;
size = 0;
return;
}
head = head.next;
head.prev=null;
size--;
return ;
}
if (index == size)
{
tail = tail.prev;
tail.next=null;
size-- ;
}
Node ptr = head.next;
for (int i = 2; i <= size; i++)
{
if (i == index)
{
Node p = ptr.prev;
Node n = ptr.next;
p.next=n;
n.prev=p;
size-- ;
return;
}
ptr = ptr.next;
}
}