The Gateway to Computer Science Excellence
0 votes
477 views

Consider an implementation of unsorted single linked list. Suppose it has its representation with a head and a tail pointer (i.e. pointers to the first and last nodes of the linked list). Given the representation, which of the following operation can not be implemented in $O(1)$ time ?

  1. Insertion at the front of the linked list.
  2. Insertion at the end of the linked list.
  3. Deletion of the front node of the linked list.
  4. Deletion of the last node of the linked list.
in Others by Boss (30.8k points)
retagged by | 477 views

1 Answer

+2 votes
Best answer

A)Insertion at the front of the linked list.

new_node->next=head;
head=new_node;

$\Theta \left ( 1 \right )$

B) Insertion at the end of the linked list.

Tail->next=new_node;
new_node->next=NULL;

 $\Theta \left ( 1 \right )$

C) Deletion of the front node of the linked list.

Next_node=Head;
Head=Next_node->next;
free(Next_node);

$\Theta \left ( 1 \right )$

D)Deletion of the last node of linked list

Here although we have tail pointer but it will be of no use because there is no previous pointer (as it is single linked list).we need to have second last pointer so that we make it the last pointer and can free the last pointer i.e deleting the last node.So we need to traverse the whole linked list making it $\Theta \left ( n \right )$.

struct node *p,*prev;
p=head;
while(p)
{
    prev=p;
    p=p->next;
}
prev->next=NULL;
free(p);

ANSWER D)

by Boss (16.2k points)
selected by
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,385 answers
198,557 comments
105,368 users