DS 03 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Data Structures

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

A next B next C next

head temp next


NULL

20-08-2020 6
Insert at position
• q->next = temp;
• temp->next=p;

20-08-2020 7
Insert at end

A next B next C next

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy