Lecture 10 DSA-1
Lecture 10 DSA-1
• Traversal
• Search, print, update etc.
• Insertion
• Deletion
Node
Node can be represented using either structure or
class
Class is also used in C++, but
C++we will focus on struct only. java
struct Node class Node
{ {
int data; int data;
Node *next; Node next;
Node Operations: } }
Constructing a new
node Node* node=new Node Node node=new Node()
class Student{
private String name;
private float gpa;
private Student next;
}
class Book{
1099
data 1009
Insertion at End
If List is Empty Non-Empty
head NULL List 1009 1001
head data data NULL
1001
Create a Node and Update Head Create new node
1009 1009 1001
head data NULL head data 1001 data 1099
Now this will become 3rd node and new node will be inserted before this node.
prev curr
So when new node is inserted, we can easily change next links of new node
and previous node.
1009 1001 1099
head 9 1019 7 1099 11
1019 NULL
13 1001
Deletio
n
Deleting a new node involves two things:
Unlinking the node in a way that its logical predecessor gets connected to next node of
list to maintain linking
There can be three scenarios to delete node
Deletion from Start
Deletion from End
Deletion from Middle
Deletio
n
Deletion From Start
1009 1001 1099
head 9 1001 7 1099 11
NULL
1001 1099
head 7 1099 11
NULL
Deletion From End
1009 1001 1099
head 9 1001 7 1099 11
NULL
1009 1001
head 9 1001 7 NULL
DELETE
Algorithm: DELETE_END(Head)
Input: reference to first node
Output: new list with lat node deleted
Steps:
Start:
1.If Head!=NULL// list is not empty
2. If Head.next==NULL// there is only one node
3. Head=NULL
4. Else
5. Set Curr=Head, Prev=NULL
6. While (Curr.next!=NULL)
7. Prev=Curr
8. Curr=Curr.next
9. End While
10. Prev.next=NULL
11. End If
12.End If
End
Deletio
n
Deletion at Location
This case involves searching a specific node to delete
We also need to find current and previous node pointers in order to maintain
links.
Current will be our required node. Let say we need to delete 2nd from following
list
We need to search 2nd in list, and then need to find its previous node also, so before
1009 1001 1099
deletion we can link previous node to next node of 2nd node
head 9 1001 7 1099 11
NULL
prev curr
Deletion
1009 1001 1099
head 9 1001 7 1099 11
NULL
prev curr
prev curr
1009 1099
head 9 1099 11
NULL
THE END