Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
+1 vote
1.7k views
in Computer by (69.2k points)

Write an O(1) algorithm to delete a node p in a singly linked list. Can we use this algorithm to delete every node? Justify

1 Answer

+2 votes
by (69.8k points)
selected by
 
Best answer

One deletion operation consists in deleting a node at the beginning of the list and returning the value stored in it. This operation is implemented by a member function delete From Head() given below. In this operation, the information from the first node is temporarily stored in local variable and then head is reset so that what was the second node becomes the first node. In this way, the former first node can be deleted in constant O(1) time.

Deleting the first node, from a linked list pointed by ‘head’ can be done is O(i) time head = head next

Deleting a note that follows a node with address P can also be done in O(i) time

But a node with address P cannot be deleted in O(i) time. It takes linear time.

//Delete the first node

delete From Head(struct node *q,int num)

{

struct node *temp;

temp=*q; 

*q=templink;

free(temp);

}

We can use this algorithm to delete every node by calling it recursively. The best case is when the head node is to be deleted, which takes O(1) time to accomplish. The worst case is when the last node needs to be deleted because in that case it will take O(n) performance.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...