Singly and Doubly Linked List have the following methods: Insertion: insertAt, i
ID: 3870711 • 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 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 remove at a fixed position:
void removeAt(struct Node **head_reference, int index)
{
// If no data found
if (*head_reference == NULL)
return;
struct Node* temp = *head_reference;
// If first element needs to be removed
if (index == 0)
{
*head_reference = temp->next;
return;
}
//If index >0
for (int i=0; temp!=NULL && i<index-1; i++)
temp = temp->next;
if (temp == NULL || temp->next == NULL)
return;
struct Node *next = temp->next->next;
temp->next = next;
}
//doubly linked list insert at given position
void insertAt(int value,int index)
{
struct node* temp=NULL;
temp=(node*)malloc(sizeof(struct node));
temp->data=value;
//if head is null
if(head==NULL)
{
temp->next=NULL;
head=temp;
temp->prev=head;
}
else
{
struct node* temp2=head;
struct node* temp3=NULL;
int i=0;
for(i=0;i<index-1;i++)
{
temp2=temp2->next;
temp3=temp2->next;
}
temp->next=temp3;
temp3->prev=temp->next;
temp2->next=temp;
temp->prev=temp2;
}
}