DS 03 PDF
DS 03 PDF
DS 03 PDF
CS 201
Asst. Professor
CSE
BIT Mesra, Ranchi
20-08-2020 1
Linked Lists
• Declaration – self referenced structure
• struct node
{
int data;
struct node *next;
};
20-08-2020 2
Linked Lists
• Singly Linked Lists: Insert
• Insert node at the beginning
Here
A next B next
head
NULL
20-08-2020 3
Insert
• void insertAtBegin (struct node **head, int key, int
position)
• struct node *p, *temp;
key next
• temp=(node *)malloc(sizeof(struct node))
• If(!temp)
{
printf(“Memory Allocation error ”); temp
return;
}
• p= *head
• temp->next = p
• *head = temp
20-08-2020 4
Insert at position
• struct insertKeyAtPosition (struct node **head,
key, int position)
• struct node *p, *q, *temp;
• p = *head;
• while((p !=null) && k< position) //??
{
k++;
q=p;
p = p->next;
}
20-08-2020 5
Insert at position
• Insert key at position
q
p
20-08-2020 6
Insert at position
• q->next = temp;
• temp->next=p;
20-08-2020 7
Insert at end
temp next
NULL
20-08-2020 8
Insert at the end
• struct insertAtEnd(struct node **head, int key)
• struct node *p, *temp;
p = *head;
• While(p->next != null)
{
p = p- > next;
}
p->next = temp;
temp -> next = NULL;
20-08-2020 9
Deletion
• Deletion at the beginning
• Void deleteAtBegin(struct node **head)
• p = *head;
*head = p->next;
free(p);
20-08-2020 10
Deletion at postion
• Void deleteAtPosition(struct node
**head,postion)
• Struct node *p, *temp;
• While((p !=null) && k< position) ??
{
k++;
q=p;
p = p->next;
}
20-08-2020 11
Deletion at position
• If(p==NULL){
printf(“position not found”)
}
else{
p->next=q->next;
free(p);
}
20-08-2020 12
Deletion at the end
• Void deleteAtEnd(struct node **head)
• P = *head;
• While(p->next !=NULL){
q=p;
p = p –>next;
}
• q->next-null
• free(p)
20-08-2020 13
Traverse the list
• Void displayKeyAtPosition(struct node **head,
int position)
• Assignment-1
20-08-2020 14
Doubly linked lists
• struct node
{
int data;
struct node *left;
struct node *right;
};
A right left B right left C right
Head
20-08-2020 NULL 15
Insert
• void insertAtBegin(struct node **head, int key)
struct node *temp,*p;
temp ->data = key; //malloc
p = *head;
temp->right = p;
temp->left = NULL;
if(p) {
p->left = temp;
}
*head = temp;
20-08-2020 16