SlideShare a Scribd company logo
Data Structure
Chapter 2
Arrays and linked
lists
Odd sem 2023-24 Data Structure 1
Contents
• Linked List, Linked List v/s Array, Types of Linked List
• Singly Linked List, Circular Linked List, Doubly Linked
List,
• Operations on Singly Linked List and Doubly Linked
List,
• Singly Linked List Application
• Polynomial Representation polynomial addition
Odd sem 2023-24 Data Structure 2
Introduction to Linked List
• A linked list is a data structure which can change
during execution.
– Successive elements are connected by pointers.
– Last element points to NULL.
– It can grow or shrink in size during execution of a
program.
– It can be made just as long as required.
– It does not waste memory space.
Odd sem 2023-24 Data Structure 3
A B C
head
Introduction to Linked List
• Keeping track of a linked list:
– Must know the pointer to the first element of the
list (called start, head, etc.).
• Linked lists provide flexibility in allowing the
items to be rearranged efficiently.
– Insert an element.
– Delete an element.
Odd sem 2023-24 Data Structure 4
Array versus Linked Lists
• Arrays are suitable for:
– Inserting/deleting an element at the end.
– Randomly accessing any element.
– Searching the list for a particular value.
• Linked lists are suitable for:
– Inserting an element.
– Deleting an element.
– Applications where sequential access is required.
– In situations where the number of elements cannot
be predicted beforehand.
Odd sem 2023-24 Data Structure 5
Types of Lists
• Depending on the way in which the links are
used to maintain adjacency, several different
types of linked lists are possible.
– Linear singly-linked list (or simply linear list)
• One we have discussed so far.
Odd sem 2023-24 Data Structure 6
A B C
head
– Circular linked list
• The pointer from the last element in the list points back
to the first element.
Odd sem 2023-24 Data Structure 7
A B C
head
– Doubly linked list
• Pointers exist between adjacent nodes in both
directions.
• The list can be traversed either forward or backward.
• Usually two pointers are maintained to keep track of
the list, head and tail.
Odd sem 2023-24 Data Structure 8
A B C
head tail
Basic Operations on a List
• Creating a list
• Traversing the list
• Inserting an item in the list
• Deleting an item from the list
• Concatenating two lists into one
Odd sem 2023-24 Data Structure 9
List is an Abstract Data Type
• What is an abstract data type?
– It is a data type defined by the user.
– Typically more complex than simple data types like
int, float, etc.
• Why abstract?
– Because details of the implementation are hidden.
– When you do some operation on the list, say insert
an element, you just call a function.
– Details of how the list is implemented or how the
insert function is written is no longer required.
Odd sem 2023-24 Data Structure 10
Conceptual Idea
Odd sem 2023-24 Data Structure 11
List
implementation
and the
related functions
Insert
Delete
Traverse
Example: Working with linked list
• Consider the structure of a node as follows:
struct stud {
int roll;
char name[25];
int age;
struct stud *next;
};
/* A user-defined data type called “node” */
typedef struct stud node;
node *head;
Odd sem 2023-24 Data Structure 12
Creating a List
Odd sem 2023-24 Data Structure 13
How to begin?
• To start with, we have to create a node (the
first node), and make head point to it.
head = (node *)
malloc(sizeof(node));
Odd sem 2023-24 Data Structure 14
head
age
name
roll
next
Contd.
• If there are n number of nodes in the initial
linked list:
– Allocate n records, one by one.
– Read in the fields of the records.
– Modify the links of the records so that the chain is
formed.
Odd sem 2023-24 Data Structure 15
A B C
head
node *create_list()
{
int k, n;
node *p, *head;
printf ("n How many elements to enter?");
scanf ("%d", &n);
for (k=0; k<n; k++)
{
if (k == 0) {
head = (node *) malloc(sizeof(node));
p = head;
}
else {
p->next = (node *) malloc(sizeof(node));
p = p->next;
}
scanf ("%d %s %d", &p->roll, p->name, &p->age);
}
p->next = NULL;
return (head);
}
Odd sem 2023-24 Data Structure 16
• To be called from main() function as:
node *head;
………
head = create_list();
Odd sem 2023-24 Data Structure 17
Traversing the List
Odd sem 2023-24 Data Structure 18
What is to be done?
• Once the linked list has been constructed and
head points to the first node of the list,
– Follow the pointers.
– Display the contents of the nodes as they are
traversed.
– Stop when the next pointer points to NULL.
Odd sem 2023-24 Data Structure 19
void display (node *head)
{
int count = 1;
node *p;
p = head;
while (p != NULL)
{
printf ("nNode %d: %d %s %d", count,
p->roll, p->name, p->age);
count++;
p = p->next;
}
printf ("n");
}
Odd sem 2023-24 Data Structure 20
• To be called from main() function as:
node *head;
………
display (head);
Odd sem 2023-24 Data Structure 21
Inserting a Node in a List
Odd sem 2023-24 Data Structure 22
How to do?
• The problem is to insert a node before a
specified node.
– Specified means some value is given for the node
(called key).
– In this example, we consider it to be roll.
• Convention followed:
– If the value of roll is given as negative, the node
will be inserted at the end of the list.
Odd sem 2023-24 Data Structure 23
Contd.
• When a node is added at the beginning,
– Only one next pointer needs to be modified.
• head is made to point to the new node.
• New node points to the previously first element.
• When a node is added at the end,
– Two next pointers need to be modified.
• Last node now points to the new node.
• New node points to NULL.
• When a node is added in the middle,
– Two next pointers need to be modified.
• Previous node now points to the new node.
• New node points to the next node.
Odd sem 2023-24 Data Structure 24
Odd sem 2023-24 Data Structure 25
void insert (node **head)
{
int k = 0, rno;
node *p, *q, *new;
new = (node *) malloc(sizeof(node));
printf ("nData to be inserted: ");
scanf ("%d %s %d", &new->roll, new->name, &new->age);
printf ("nInsert before roll (-ve for end):");
scanf ("%d", &rno);
p = *head;
if (p->roll == rno) /* At the beginning */
{
new->next = p;
*head = new;
}
Odd sem 2023-24 Data Structure 26
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
if (p == NULL) /* At the end */
{
q->next = new;
new->next = NULL;
}
else if (p->roll == rno)
/* In the middle */
{
q->next = new;
new->next = p;
}
}
}
The pointers
q and p
always point
to consecutive
nodes.
• To be called from main() function as:
node *head;
………
insert (&head);
Odd sem 2023-24 Data Structure 27
Deleting a node from the list
Odd sem 2023-24 Data Structure 28
Illustration: Deletion
Odd sem 2023-24 Data Structure 29
A B
A B C
C
Item to be deleted
curr
tmp
Pseudo-code for deletion
Odd sem 2023-24 Data Structure 30
typedef struct nd {
struct item data;
struct nd * next;
} node;
void delete(node *curr)
{
node * tmp;
tmp=curr->next;
curr->next=tmp->next;
free(tmp);
}
Illustration: Insertion
Odd sem 2023-24 Data Structure 31
A
A
Item to be
inserted
X
X
A B C
B C
curr
tmp
Pseudo-code for insertion
Odd sem 2023-24 Data Structure 32
typedef struct nd {
struct item data;
struct nd * next;
} node;
void insert(node *curr)
{
node * tmp;
tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
What is to be done?
• Here also we are required to delete a specified
node.
– Say, the node whose roll field is given.
• Here also three conditions arise:
– Deleting the first node.
– Deleting the last node.
– Deleting an intermediate node.
Odd sem 2023-24 Data Structure 33
Odd sem 2023-24 Data Structure 34
void delete (node **head)
{
int rno;
node *p, *q;
printf ("nDelete for roll :");
scanf ("%d", &rno);
p = *head;
if (p->roll == rno)
/* Delete the first element */
{
*head = p->next;
free (p);
}
Odd sem 2023-24 Data Structure 35
else
{
while ((p != NULL) && (p->roll != rno))
{
q = p;
p = p->next;
}
if (p == NULL) /* Element not found */
printf ("nNo match :: deletion failed");
else if (p->roll == rno)
/* Delete any other element */
{
q->next = p->next;
free (p);
}
}
}
In essence ...
• For insertion:
– A record is created holding the new item.
– The next pointer of the new record is set to link it to
the item which is to follow it in the list.
– The next pointer of the item which is to precede it
must be modified to point to the new item.
• For deletion:
– The next pointer of the item immediately preceding
the one to be deleted is altered, and made to point
to the item following the deleted item.
Odd sem 2023-24 Data Structure 36
Few Exercises to Try Out
• Write a function to:
– Concatenate two given list into one big list.
node *concatenate (node *head1, node *head2);
– Insert an element in a linked list in sorted order.
The function will be called for every element to
be inserted.
void insert_sorted (node **head, node *element);
– Always insert elements at one end, and delete
elements from the other end (first-in first-out
QUEUE).
void insert_q (node **head, node *element)
node *delete_q (node **head) /* Return the deleted node */
Odd sem 2023-24 Data Structure 37
A First-in First-out (FIFO) List
Odd sem 2023-24 Data Structure 38
Also called a QUEUE
In Out
A
C B
A
B
A Last-in First-out (LIFO) List
Odd sem 2023-24 Data Structure 39
In Out
A
B
C C
B
Also called a
STACK
Abstract Data Types
Odd sem 2023-24 Data Structure 40
Example 1 :: Complex numbers
struct cplx {
float re;
float im;
}
typedef struct cplx complex;
complex *add (complex a, complex b);
complex *sub (complex a, complex b);
complex *mul (complex a, complex b);
complex *div (complex a, complex b);
complex *read();
void print (complex a);
Odd sem 2023-24 Data Structure 41
Structure
definition
Function
prototypes
Odd sem 2023-24 Data Structure 42
Complex
Number
add
print
mul
sub
read
div
Example 2 :: Set manipulation
struct node {
int element;
struct node *next;
}
typedef struct node set;
set *union (set a, set b);
set *intersect (set a, set b);
set *minus (set a, set b);
void insert (set a, int x);
void delete (set a, int x);
int size (set a);
Odd sem 2023-24 Data Structure 43
Structure
definition
Function
prototypes
Odd sem 2023-24 Data Structure 44
Set
union
size
minus
intersect
delete
insert
Example 3 :: Last-In-First-Out STACK
Assume:: stack contains integer elements
void push (stack *s, int element);
/* Insert an element in the stack */
int pop (stack *s);
/* Remove and return the top element */
void create (stack *s);
/* Create a new stack */
int isempty (stack *s);
/* Check if stack is empty */
int isfull (stack *s);
/* Check if stack is full */
Odd sem 2023-24 Data Structure 45
Odd sem 2023-24 Data Structure 46
STACK
push
create
pop
isfull
isempty
Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list
Odd sem 2023-24 Data Structure 47
Example 4 :: First-In-First-Out
QUEUE
Assume:: queue contains integer elements
void enqueue (queue *q, int element);
/* Insert an element in the queue */
int dequeue (queue *q);
/* Remove an element from the queue */
queue *create();
/* Create a new queue */
int isempty (queue *q);
/* Check if queue is empty */
int size (queue *q);
/* Return the no. of elements in queue */
Odd sem 2023-24 Data Structure 48
Odd sem 2023-24 Data Structure 49
QUEUE
enqueue
create
dequeue
size
isempty
Stack Implementations: Using Array
and Linked List
Odd sem 2023-24 Data Structure 50
STACK USING ARRAY
Odd sem 2023-24 Data Structure 51
top
top
PUSH
STACK USING ARRAY
Odd sem 2023-24 Data Structure 52
top
top
POP
Stack: Linked List Structure
Odd sem 2023-24 Data Structure 53
top
PUSH OPERATION
Stack: Linked List Structure
Odd sem 2023-24 Data Structure 54
top
POP OPERATION
Basic Idea
• In the array implementation, we would:
– Declare an array of fixed size (which determines the maximum size of
the stack).
– Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.
• In the linked list implementation, we would:
– Maintain the stack as a linked list.
– A pointer variable top points to the start of the list.
– The first element of the linked list is considered as the stack top.
Odd sem 2023-24 Data Structure 56
Declaration
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo
stack;
stack s;
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo
stack;
stack *top;
Odd sem 2023-24 Data Structure 57
ARRAY LINKED LIST
Stack Creation
void create (stack *s)
{
s->top = -1;
/* s->top points to
last element
pushed in;
initially -1 */
}
void create (stack **top)
{
*top = NULL;
/* top points to NULL,
indicating empty
stack */
}
Odd sem 2023-24 Data Structure 58
ARRAY
LINKED LIST
Pushing an element into the stack
void push (stack *s, int element)
{
if (s->top == (MAXSIZE-1))
{
printf (“n Stack overflow”);
exit(-1);
}
else
{
s->top ++;
s->st[s->top] = element;
}
}
Odd sem 2023-24 Data Structure 59
ARRAY
void push (stack **top, int element)
{
stack *new;
new = (stack *) malloc(sizeof(stack));
if (new == NULL)
{
printf (“n Stack is full”);
exit(-1);
}
new->value = element;
new->next = *top;
*top = new;
}
Odd sem 2023-24 Data Structure 60
LINKED LIST
Popping an element from the stack
int pop (stack *s)
{
if (s->top == -1)
{
printf (“n Stack underflow”);
exit(-1);
}
else
{
return (s->st[s->top--]);
}
}
Odd sem 2023-24 Data Structure 61
ARRAY
int pop (stack **top)
{
int t;
stack *p;
if (*top == NULL)
{
printf (“n Stack is empty”);
exit(-1);
}
else
{
t = (*top)->value;
p = *top;
*top = (*top)->next;
free (p);
return t;
}
}
Odd sem 2023-24 Data Structure 62
LINKED LIST
Checking for stack empty
int isempty (stack *s)
{
if (s->top == -1)
return 1;
else
return (0);
}
int isempty (stack *top)
{
if (top == NULL)
return (1);
else
return (0);
}
Odd sem 2023-24 Data Structure 63
ARRAY LINKED LIST
Checking for stack full
int isfull (stack *s)
{
if (s->top ==
(MAXSIZE–1))
return 1;
else
return (0);
}
• Not required for linked list
implementation.
• In the push() function, we
can check the return value of
malloc().
– If -1, then memory cannot be
allocated.
Odd sem 2023-24 Data Structure 64
ARRAY LINKED LIST
Example main function :: array
#include <stdio.h>
#define MAXSIZE 100
struct lifo
{
int st[MAXSIZE];
int top;
};
typedef struct lifo stack;
main()
{
stack A, B;
create(&A); create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100); push(&B,5);
printf (“%d %d”, pop(&A),
pop(&B));
push (&A, pop(&B));
if (isempty(&B))
printf (“n B is empty”);
}
Odd sem 2023-24 Data Structure 65
Example main function :: linked list
#include <stdio.h>
struct lifo
{
int value;
struct lifo *next;
};
typedef struct lifo stack;
main()
{
stack *A, *B;
create(&A); create(&B);
push(&A,10);
push(&A,20);
push(&A,30);
push(&B,100);
push(&B,5);
printf (“%d %d”,
pop(&A), pop(&B));
push (&A, pop(&B));
if (isempty(B))
printf (“n B is
empty”);
}
Odd sem 2023-24 Data Structure 66
Queue Implementation using Linked
List
Odd sem 2023-24 Data Structure 67
Basic Idea
• Basic idea:
– Create a linked list to which items would be added
to one end and deleted from the other end.
– Two pointers will be maintained:
• One pointing to the beginning of the list (point from
where elements will be deleted).
• Another pointing to the end of the list (point where
new elements will be inserted).
Odd sem 2023-24 Data Structure 68
Front
Rear
DELETION INSERTION
QUEUE: LINKED LIST STRUCTURE
Odd sem 2023-24 Data Structure 69
front rear
ENQUEUE
QUEUE: LINKED LIST STRUCTURE
Odd sem 2023-24 Data Structure 70
front rear
DEQUEUE
QUEUE using Linked List
Odd sem 2023-24 Data Structure 71
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node{
char name[30];
struct node *next;
};
typedef struct node _QNODE;
typedef struct {
_QNODE *queue_front, *queue_rear;
} _QUEUE;
Odd sem 2023-24 Data Structure 72
_QNODE *enqueue (_QUEUE *q, char x[])
{
_QNODE *temp;
temp= (_QNODE *)
malloc (sizeof(_QNODE));
if (temp==NULL){
printf(“Bad allocation n");
return NULL;
}
strcpy(temp->name,x);
temp->next=NULL;
if(q->queue_rear==NULL)
{
q->queue_rear=temp;
q->queue_front=
q->queue_rear;
}
else
{
q->queue_rear->next=temp;
q->queue_rear=temp;
}
return(q->queue_rear);
}
Odd sem 2023-24 Data Structure 73
char *dequeue(_QUEUE *q,char x[])
{
_QNODE *temp_pnt;
if(q->queue_front==NULL){
q->queue_rear=NULL;
printf("Queue is empty n");
return(NULL);
}
else{
strcpy(x,q->queue_front->name);
temp_pnt=q->queue_front;
q->queue_front=
q->queue_front->next;
free(temp_pnt);
if(q->queue_front==NULL)
q->queue_rear=NULL;
return(x);
}
}
Odd sem 2023-24 Data Structure 74
void init_queue(_QUEUE *q)
{
q->queue_front= q->queue_rear=NULL;
}
int isEmpty(_QUEUE *q)
{
if(q==NULL) return 1;
else return 0;
}
Odd sem 2023-24 Data Structure 75
main()
{
int i,j;
char command[5],val[30];
_QUEUE q;
init_queue(&q);
command[0]='0';
printf("For entering a name use 'enter <name>'n");
printf("For deleting use 'delete' n");
printf("To end the session use 'bye' n");
while(strcmp(command,"bye")){
scanf("%s",command);
Odd sem 2023-24 Data Structure 76
if(!strcmp(command,"enter")) {
scanf("%s",val);
if((enqueue(&q,val)==NULL))
printf("No more pushing please n");
else printf("Name entered %s n",val);
}
if(!strcmp(command,"delete")) {
if(!isEmpty(&q))
printf("%s n",dequeue(&q,val));
else printf("Name deleted %s n",val);
}
} /* while */
printf("End session n");
}
Problem With Array Implementation
Odd sem 2023-24 Data Structure 77
front rear
rear
ENQUEUE
front
DEQUEUE
Effective queuing storage area of array gets reduced.
Use of circular array indexing
0 N
Queue: Example with Array Implementation
Odd sem 2023-24 Data Structure 78
typedef struct { char name[30];
} _ELEMENT;
typedef struct {
_ELEMENT q_elem[MAX_SIZE];
int rear;
int front;
int full,empty;
} _QUEUE;
#define MAX_SIZE 100
Queue Example: Contd.
Odd sem 2023-24 Data Structure 79
void init_queue(_QUEUE *q)
{q->rear= q->front= 0;
q->full=0; q->empty=1;
}
int IsFull(_QUEUE *q)
{return(q->full);}
int IsEmpty(_QUEUE *q)
{return(q->empty);}
Queue Example: Contd.
Odd sem 2023-24 Data Structure 80
void AddQ(_QUEUE *q, _ELEMENT ob)
{
if(IsFull(q)) {printf("Queue is Full n"); return;}
q->rear=(q->rear+1)%(MAX_SIZE);
q->q_elem[q->rear]=ob;
if(q->front==q->rear) q->full=1; else q->full=0;
q->empty=0;
return;
}
Queue Example: Contd.
Odd sem 2023-24 Data Structure 81
_ELEMENT DeleteQ(_QUEUE *q)
{
_ELEMENT temp;
temp.name[0]='0';
if(IsEmpty(q)) {printf("Queue is EMPTYn");return(temp);}
q->front=(q->front+1)%(MAX_SIZE);
temp=q->q_elem[q->front];
if(q->rear==q->front) q->empty=1; else q->empty=0;
q->full=0;
return(temp);
}
Queue Example: Contd.
Odd sem 2023-24 Data Structure 82
main()
{
int i,j;
char command[5];
_ELEMENT ob;
_QUEUE A;
init_queue(&A);
command[0]='0';
printf("For adding a name use 'add [name]'n");
printf("For deleting use 'delete' n");
printf("To end the session use 'bye' n");
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Queue Example: Contd.
Odd sem 2023-24 Data Structure 83
while (strcmp(command,"bye")!=0){
scanf("%s",command);
if(strcmp(command,"add")==0) {
scanf("%s",ob.name);
if (IsFull(&A))
printf("No more insertion please n");
else {
AddQ(&A,ob);
printf("Name inserted %s n",ob.name);
}
}
Queue Example: Contd.
Odd sem 2023-24 Data Structure 84
if (strcmp(command,"delete")==0) {
if (IsEmpty(&A))
printf("Queue is empty n");
else {
ob=DeleteQ(&A);
printf("Name deleted %s n",ob.name);
}
}
} /* End of while */
printf("End session n");
}

More Related Content

Similar to linkedlist (1).ppt

cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
RahulYadav738822
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
Afaq Mansoor Khan
 
linked list
linked listlinked list
linked list
Abbott
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
mrizwan38
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
Hanif Durad
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
Mani .S (Specialization in Semantic Web)
 
linkedLists.ppt
linkedLists.pptlinkedLists.ppt
linkedLists.ppt
Sachin266673
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
Durga Devi
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
SrinivasanCSE
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
kiran Patel
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
Khulna University of Engineering & Tecnology
 
Linked Lists.pdf
Linked Lists.pdfLinked Lists.pdf
Linked Lists.pdf
Kaynattariq1
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
FaheemMahmood2
 
linklked lisdi.pdf
linklked lisdi.pdflinklked lisdi.pdf
linklked lisdi.pdf
VinayKamriya
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsAakash deep Singhal
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
Bharati Vidyapeeth COE, Navi Mumbai
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
ASADAHMAD811380
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
SonaPathak5
 

Similar to linkedlist (1).ppt (20)

cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Doubly & Circular Linked Lists
Doubly & Circular Linked ListsDoubly & Circular Linked Lists
Doubly & Circular Linked Lists
 
Data structures
Data structuresData structures
Data structures
 
linked list
linked listlinked list
linked list
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Unit II  Data Structure 2hr topic - List - Operations.pptxUnit II  Data Structure 2hr topic - List - Operations.pptx
Unit II Data Structure 2hr topic - List - Operations.pptx
 
linkedLists.ppt
linkedLists.pptlinkedLists.ppt
linkedLists.ppt
 
Unit ii(dsc++)
Unit ii(dsc++)Unit ii(dsc++)
Unit ii(dsc++)
 
Linked list
Linked listLinked list
Linked list
 
12888239 (2).ppt
12888239 (2).ppt12888239 (2).ppt
12888239 (2).ppt
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
 
Singly & Circular Linked list
Singly & Circular Linked listSingly & Circular Linked list
Singly & Circular Linked list
 
Linked Lists.pdf
Linked Lists.pdfLinked Lists.pdf
Linked Lists.pdf
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
linklked lisdi.pdf
linklked lisdi.pdflinklked lisdi.pdf
linklked lisdi.pdf
 
Lecture 4 data structures and algorithms
Lecture 4 data structures and algorithmsLecture 4 data structures and algorithms
Lecture 4 data structures and algorithms
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
 
csc211_lecture_21.pptx
csc211_lecture_21.pptxcsc211_lecture_21.pptx
csc211_lecture_21.pptx
 
DS Module 03.pdf
DS Module 03.pdfDS Module 03.pdf
DS Module 03.pdf
 

Recently uploaded

Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Subhajit Sahu
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
mbawufebxi
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar
 
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdfSample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Linda486226
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
ewymefz
 
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
axoqas
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
ahzuo
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
oz8q3jxlp
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
axoqas
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
Opendatabay
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
AbhimanyuSinha9
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
nscud
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
nscud
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
haila53
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
ArpitMalhotra16
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
pchutichetpong
 
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
Tiktokethiodaily
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
TravisMalana
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
Oppotus
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
yhkoc
 

Recently uploaded (20)

Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
Algorithmic optimizations for Dynamic Levelwise PageRank (from STICD) : SHORT...
 
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
一比一原版(Bradford毕业证书)布拉德福德大学毕业证如何办理
 
SOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape ReportSOCRadar Germany 2024 Threat Landscape Report
SOCRadar Germany 2024 Threat Landscape Report
 
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdfSample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
Sample_Global Non-invasive Prenatal Testing (NIPT) Market, 2019-2030.pdf
 
一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单一比一原版(NYU毕业证)纽约大学毕业证成绩单
一比一原版(NYU毕业证)纽约大学毕业证成绩单
 
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
做(mqu毕业证书)麦考瑞大学毕业证硕士文凭证书学费发票原版一模一样
 
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
一比一原版(UIUC毕业证)伊利诺伊大学|厄巴纳-香槟分校毕业证如何办理
 
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
一比一原版(Deakin毕业证书)迪肯大学毕业证如何办理
 
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
哪里卖(usq毕业证书)南昆士兰大学毕业证研究生文凭证书托福证书原版一模一样
 
Opendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptxOpendatabay - Open Data Marketplace.pptx
Opendatabay - Open Data Marketplace.pptx
 
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...Best best suvichar in gujarati english meaning of this sentence as Silk road ...
Best best suvichar in gujarati english meaning of this sentence as Silk road ...
 
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
一比一原版(CBU毕业证)不列颠海角大学毕业证成绩单
 
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
一比一原版(CBU毕业证)卡普顿大学毕业证成绩单
 
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdfCh03-Managing the Object-Oriented Information Systems Project a.pdf
Ch03-Managing the Object-Oriented Information Systems Project a.pdf
 
standardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghhstandardisation of garbhpala offhgfffghh
standardisation of garbhpala offhgfffghh
 
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
Data Centers - Striving Within A Narrow Range - Research Report - MCG - May 2...
 
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
1.Seydhcuxhxyxhccuuxuxyxyxmisolids 2019.pptx
 
Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)Malana- Gimlet Market Analysis (Portfolio 2)
Malana- Gimlet Market Analysis (Portfolio 2)
 
Q1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year ReboundQ1’2024 Update: MYCI’s Leap Year Rebound
Q1’2024 Update: MYCI’s Leap Year Rebound
 
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
一比一原版(CU毕业证)卡尔顿大学毕业证成绩单
 

linkedlist (1).ppt

  • 1. Data Structure Chapter 2 Arrays and linked lists Odd sem 2023-24 Data Structure 1
  • 2. Contents • Linked List, Linked List v/s Array, Types of Linked List • Singly Linked List, Circular Linked List, Doubly Linked List, • Operations on Singly Linked List and Doubly Linked List, • Singly Linked List Application • Polynomial Representation polynomial addition Odd sem 2023-24 Data Structure 2
  • 3. Introduction to Linked List • A linked list is a data structure which can change during execution. – Successive elements are connected by pointers. – Last element points to NULL. – It can grow or shrink in size during execution of a program. – It can be made just as long as required. – It does not waste memory space. Odd sem 2023-24 Data Structure 3 A B C head
  • 4. Introduction to Linked List • Keeping track of a linked list: – Must know the pointer to the first element of the list (called start, head, etc.). • Linked lists provide flexibility in allowing the items to be rearranged efficiently. – Insert an element. – Delete an element. Odd sem 2023-24 Data Structure 4
  • 5. Array versus Linked Lists • Arrays are suitable for: – Inserting/deleting an element at the end. – Randomly accessing any element. – Searching the list for a particular value. • Linked lists are suitable for: – Inserting an element. – Deleting an element. – Applications where sequential access is required. – In situations where the number of elements cannot be predicted beforehand. Odd sem 2023-24 Data Structure 5
  • 6. Types of Lists • Depending on the way in which the links are used to maintain adjacency, several different types of linked lists are possible. – Linear singly-linked list (or simply linear list) • One we have discussed so far. Odd sem 2023-24 Data Structure 6 A B C head
  • 7. – Circular linked list • The pointer from the last element in the list points back to the first element. Odd sem 2023-24 Data Structure 7 A B C head
  • 8. – Doubly linked list • Pointers exist between adjacent nodes in both directions. • The list can be traversed either forward or backward. • Usually two pointers are maintained to keep track of the list, head and tail. Odd sem 2023-24 Data Structure 8 A B C head tail
  • 9. Basic Operations on a List • Creating a list • Traversing the list • Inserting an item in the list • Deleting an item from the list • Concatenating two lists into one Odd sem 2023-24 Data Structure 9
  • 10. List is an Abstract Data Type • What is an abstract data type? – It is a data type defined by the user. – Typically more complex than simple data types like int, float, etc. • Why abstract? – Because details of the implementation are hidden. – When you do some operation on the list, say insert an element, you just call a function. – Details of how the list is implemented or how the insert function is written is no longer required. Odd sem 2023-24 Data Structure 10
  • 11. Conceptual Idea Odd sem 2023-24 Data Structure 11 List implementation and the related functions Insert Delete Traverse
  • 12. Example: Working with linked list • Consider the structure of a node as follows: struct stud { int roll; char name[25]; int age; struct stud *next; }; /* A user-defined data type called “node” */ typedef struct stud node; node *head; Odd sem 2023-24 Data Structure 12
  • 13. Creating a List Odd sem 2023-24 Data Structure 13
  • 14. How to begin? • To start with, we have to create a node (the first node), and make head point to it. head = (node *) malloc(sizeof(node)); Odd sem 2023-24 Data Structure 14 head age name roll next
  • 15. Contd. • If there are n number of nodes in the initial linked list: – Allocate n records, one by one. – Read in the fields of the records. – Modify the links of the records so that the chain is formed. Odd sem 2023-24 Data Structure 15 A B C head
  • 16. node *create_list() { int k, n; node *p, *head; printf ("n How many elements to enter?"); scanf ("%d", &n); for (k=0; k<n; k++) { if (k == 0) { head = (node *) malloc(sizeof(node)); p = head; } else { p->next = (node *) malloc(sizeof(node)); p = p->next; } scanf ("%d %s %d", &p->roll, p->name, &p->age); } p->next = NULL; return (head); } Odd sem 2023-24 Data Structure 16
  • 17. • To be called from main() function as: node *head; ……… head = create_list(); Odd sem 2023-24 Data Structure 17
  • 18. Traversing the List Odd sem 2023-24 Data Structure 18
  • 19. What is to be done? • Once the linked list has been constructed and head points to the first node of the list, – Follow the pointers. – Display the contents of the nodes as they are traversed. – Stop when the next pointer points to NULL. Odd sem 2023-24 Data Structure 19
  • 20. void display (node *head) { int count = 1; node *p; p = head; while (p != NULL) { printf ("nNode %d: %d %s %d", count, p->roll, p->name, p->age); count++; p = p->next; } printf ("n"); } Odd sem 2023-24 Data Structure 20
  • 21. • To be called from main() function as: node *head; ……… display (head); Odd sem 2023-24 Data Structure 21
  • 22. Inserting a Node in a List Odd sem 2023-24 Data Structure 22
  • 23. How to do? • The problem is to insert a node before a specified node. – Specified means some value is given for the node (called key). – In this example, we consider it to be roll. • Convention followed: – If the value of roll is given as negative, the node will be inserted at the end of the list. Odd sem 2023-24 Data Structure 23
  • 24. Contd. • When a node is added at the beginning, – Only one next pointer needs to be modified. • head is made to point to the new node. • New node points to the previously first element. • When a node is added at the end, – Two next pointers need to be modified. • Last node now points to the new node. • New node points to NULL. • When a node is added in the middle, – Two next pointers need to be modified. • Previous node now points to the new node. • New node points to the next node. Odd sem 2023-24 Data Structure 24
  • 25. Odd sem 2023-24 Data Structure 25 void insert (node **head) { int k = 0, rno; node *p, *q, *new; new = (node *) malloc(sizeof(node)); printf ("nData to be inserted: "); scanf ("%d %s %d", &new->roll, new->name, &new->age); printf ("nInsert before roll (-ve for end):"); scanf ("%d", &rno); p = *head; if (p->roll == rno) /* At the beginning */ { new->next = p; *head = new; }
  • 26. Odd sem 2023-24 Data Structure 26 else { while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* At the end */ { q->next = new; new->next = NULL; } else if (p->roll == rno) /* In the middle */ { q->next = new; new->next = p; } } } The pointers q and p always point to consecutive nodes.
  • 27. • To be called from main() function as: node *head; ……… insert (&head); Odd sem 2023-24 Data Structure 27
  • 28. Deleting a node from the list Odd sem 2023-24 Data Structure 28
  • 29. Illustration: Deletion Odd sem 2023-24 Data Structure 29 A B A B C C Item to be deleted curr tmp
  • 30. Pseudo-code for deletion Odd sem 2023-24 Data Structure 30 typedef struct nd { struct item data; struct nd * next; } node; void delete(node *curr) { node * tmp; tmp=curr->next; curr->next=tmp->next; free(tmp); }
  • 31. Illustration: Insertion Odd sem 2023-24 Data Structure 31 A A Item to be inserted X X A B C B C curr tmp
  • 32. Pseudo-code for insertion Odd sem 2023-24 Data Structure 32 typedef struct nd { struct item data; struct nd * next; } node; void insert(node *curr) { node * tmp; tmp=(node *) malloc(sizeof(node)); tmp->next=curr->next; curr->next=tmp; }
  • 33. What is to be done? • Here also we are required to delete a specified node. – Say, the node whose roll field is given. • Here also three conditions arise: – Deleting the first node. – Deleting the last node. – Deleting an intermediate node. Odd sem 2023-24 Data Structure 33
  • 34. Odd sem 2023-24 Data Structure 34 void delete (node **head) { int rno; node *p, *q; printf ("nDelete for roll :"); scanf ("%d", &rno); p = *head; if (p->roll == rno) /* Delete the first element */ { *head = p->next; free (p); }
  • 35. Odd sem 2023-24 Data Structure 35 else { while ((p != NULL) && (p->roll != rno)) { q = p; p = p->next; } if (p == NULL) /* Element not found */ printf ("nNo match :: deletion failed"); else if (p->roll == rno) /* Delete any other element */ { q->next = p->next; free (p); } } }
  • 36. In essence ... • For insertion: – A record is created holding the new item. – The next pointer of the new record is set to link it to the item which is to follow it in the list. – The next pointer of the item which is to precede it must be modified to point to the new item. • For deletion: – The next pointer of the item immediately preceding the one to be deleted is altered, and made to point to the item following the deleted item. Odd sem 2023-24 Data Structure 36
  • 37. Few Exercises to Try Out • Write a function to: – Concatenate two given list into one big list. node *concatenate (node *head1, node *head2); – Insert an element in a linked list in sorted order. The function will be called for every element to be inserted. void insert_sorted (node **head, node *element); – Always insert elements at one end, and delete elements from the other end (first-in first-out QUEUE). void insert_q (node **head, node *element) node *delete_q (node **head) /* Return the deleted node */ Odd sem 2023-24 Data Structure 37
  • 38. A First-in First-out (FIFO) List Odd sem 2023-24 Data Structure 38 Also called a QUEUE In Out A C B A B
  • 39. A Last-in First-out (LIFO) List Odd sem 2023-24 Data Structure 39 In Out A B C C B Also called a STACK
  • 40. Abstract Data Types Odd sem 2023-24 Data Structure 40
  • 41. Example 1 :: Complex numbers struct cplx { float re; float im; } typedef struct cplx complex; complex *add (complex a, complex b); complex *sub (complex a, complex b); complex *mul (complex a, complex b); complex *div (complex a, complex b); complex *read(); void print (complex a); Odd sem 2023-24 Data Structure 41 Structure definition Function prototypes
  • 42. Odd sem 2023-24 Data Structure 42 Complex Number add print mul sub read div
  • 43. Example 2 :: Set manipulation struct node { int element; struct node *next; } typedef struct node set; set *union (set a, set b); set *intersect (set a, set b); set *minus (set a, set b); void insert (set a, int x); void delete (set a, int x); int size (set a); Odd sem 2023-24 Data Structure 43 Structure definition Function prototypes
  • 44. Odd sem 2023-24 Data Structure 44 Set union size minus intersect delete insert
  • 45. Example 3 :: Last-In-First-Out STACK Assume:: stack contains integer elements void push (stack *s, int element); /* Insert an element in the stack */ int pop (stack *s); /* Remove and return the top element */ void create (stack *s); /* Create a new stack */ int isempty (stack *s); /* Check if stack is empty */ int isfull (stack *s); /* Check if stack is full */ Odd sem 2023-24 Data Structure 45
  • 46. Odd sem 2023-24 Data Structure 46 STACK push create pop isfull isempty
  • 47. Contd. • We shall look into two different ways of implementing stack: – Using arrays – Using linked list Odd sem 2023-24 Data Structure 47
  • 48. Example 4 :: First-In-First-Out QUEUE Assume:: queue contains integer elements void enqueue (queue *q, int element); /* Insert an element in the queue */ int dequeue (queue *q); /* Remove an element from the queue */ queue *create(); /* Create a new queue */ int isempty (queue *q); /* Check if queue is empty */ int size (queue *q); /* Return the no. of elements in queue */ Odd sem 2023-24 Data Structure 48
  • 49. Odd sem 2023-24 Data Structure 49 QUEUE enqueue create dequeue size isempty
  • 50. Stack Implementations: Using Array and Linked List Odd sem 2023-24 Data Structure 50
  • 51. STACK USING ARRAY Odd sem 2023-24 Data Structure 51 top top PUSH
  • 52. STACK USING ARRAY Odd sem 2023-24 Data Structure 52 top top POP
  • 53. Stack: Linked List Structure Odd sem 2023-24 Data Structure 53 top PUSH OPERATION
  • 54. Stack: Linked List Structure Odd sem 2023-24 Data Structure 54 top POP OPERATION
  • 55. Basic Idea • In the array implementation, we would: – Declare an array of fixed size (which determines the maximum size of the stack). – Keep a variable which always points to the “top” of the stack. • Contains the array index of the “top” element. • In the linked list implementation, we would: – Maintain the stack as a linked list. – A pointer variable top points to the start of the list. – The first element of the linked list is considered as the stack top. Odd sem 2023-24 Data Structure 56
  • 56. Declaration #define MAXSIZE 100 struct lifo { int st[MAXSIZE]; int top; }; typedef struct lifo stack; stack s; struct lifo { int value; struct lifo *next; }; typedef struct lifo stack; stack *top; Odd sem 2023-24 Data Structure 57 ARRAY LINKED LIST
  • 57. Stack Creation void create (stack *s) { s->top = -1; /* s->top points to last element pushed in; initially -1 */ } void create (stack **top) { *top = NULL; /* top points to NULL, indicating empty stack */ } Odd sem 2023-24 Data Structure 58 ARRAY LINKED LIST
  • 58. Pushing an element into the stack void push (stack *s, int element) { if (s->top == (MAXSIZE-1)) { printf (“n Stack overflow”); exit(-1); } else { s->top ++; s->st[s->top] = element; } } Odd sem 2023-24 Data Structure 59 ARRAY
  • 59. void push (stack **top, int element) { stack *new; new = (stack *) malloc(sizeof(stack)); if (new == NULL) { printf (“n Stack is full”); exit(-1); } new->value = element; new->next = *top; *top = new; } Odd sem 2023-24 Data Structure 60 LINKED LIST
  • 60. Popping an element from the stack int pop (stack *s) { if (s->top == -1) { printf (“n Stack underflow”); exit(-1); } else { return (s->st[s->top--]); } } Odd sem 2023-24 Data Structure 61 ARRAY
  • 61. int pop (stack **top) { int t; stack *p; if (*top == NULL) { printf (“n Stack is empty”); exit(-1); } else { t = (*top)->value; p = *top; *top = (*top)->next; free (p); return t; } } Odd sem 2023-24 Data Structure 62 LINKED LIST
  • 62. Checking for stack empty int isempty (stack *s) { if (s->top == -1) return 1; else return (0); } int isempty (stack *top) { if (top == NULL) return (1); else return (0); } Odd sem 2023-24 Data Structure 63 ARRAY LINKED LIST
  • 63. Checking for stack full int isfull (stack *s) { if (s->top == (MAXSIZE–1)) return 1; else return (0); } • Not required for linked list implementation. • In the push() function, we can check the return value of malloc(). – If -1, then memory cannot be allocated. Odd sem 2023-24 Data Structure 64 ARRAY LINKED LIST
  • 64. Example main function :: array #include <stdio.h> #define MAXSIZE 100 struct lifo { int st[MAXSIZE]; int top; }; typedef struct lifo stack; main() { stack A, B; create(&A); create(&B); push(&A,10); push(&A,20); push(&A,30); push(&B,100); push(&B,5); printf (“%d %d”, pop(&A), pop(&B)); push (&A, pop(&B)); if (isempty(&B)) printf (“n B is empty”); } Odd sem 2023-24 Data Structure 65
  • 65. Example main function :: linked list #include <stdio.h> struct lifo { int value; struct lifo *next; }; typedef struct lifo stack; main() { stack *A, *B; create(&A); create(&B); push(&A,10); push(&A,20); push(&A,30); push(&B,100); push(&B,5); printf (“%d %d”, pop(&A), pop(&B)); push (&A, pop(&B)); if (isempty(B)) printf (“n B is empty”); } Odd sem 2023-24 Data Structure 66
  • 66. Queue Implementation using Linked List Odd sem 2023-24 Data Structure 67
  • 67. Basic Idea • Basic idea: – Create a linked list to which items would be added to one end and deleted from the other end. – Two pointers will be maintained: • One pointing to the beginning of the list (point from where elements will be deleted). • Another pointing to the end of the list (point where new elements will be inserted). Odd sem 2023-24 Data Structure 68 Front Rear DELETION INSERTION
  • 68. QUEUE: LINKED LIST STRUCTURE Odd sem 2023-24 Data Structure 69 front rear ENQUEUE
  • 69. QUEUE: LINKED LIST STRUCTURE Odd sem 2023-24 Data Structure 70 front rear DEQUEUE
  • 70. QUEUE using Linked List Odd sem 2023-24 Data Structure 71 #include <stdio.h> #include <stdlib.h> #include <string.h> struct node{ char name[30]; struct node *next; }; typedef struct node _QNODE; typedef struct { _QNODE *queue_front, *queue_rear; } _QUEUE;
  • 71. Odd sem 2023-24 Data Structure 72 _QNODE *enqueue (_QUEUE *q, char x[]) { _QNODE *temp; temp= (_QNODE *) malloc (sizeof(_QNODE)); if (temp==NULL){ printf(“Bad allocation n"); return NULL; } strcpy(temp->name,x); temp->next=NULL; if(q->queue_rear==NULL) { q->queue_rear=temp; q->queue_front= q->queue_rear; } else { q->queue_rear->next=temp; q->queue_rear=temp; } return(q->queue_rear); }
  • 72. Odd sem 2023-24 Data Structure 73 char *dequeue(_QUEUE *q,char x[]) { _QNODE *temp_pnt; if(q->queue_front==NULL){ q->queue_rear=NULL; printf("Queue is empty n"); return(NULL); } else{ strcpy(x,q->queue_front->name); temp_pnt=q->queue_front; q->queue_front= q->queue_front->next; free(temp_pnt); if(q->queue_front==NULL) q->queue_rear=NULL; return(x); } }
  • 73. Odd sem 2023-24 Data Structure 74 void init_queue(_QUEUE *q) { q->queue_front= q->queue_rear=NULL; } int isEmpty(_QUEUE *q) { if(q==NULL) return 1; else return 0; }
  • 74. Odd sem 2023-24 Data Structure 75 main() { int i,j; char command[5],val[30]; _QUEUE q; init_queue(&q); command[0]='0'; printf("For entering a name use 'enter <name>'n"); printf("For deleting use 'delete' n"); printf("To end the session use 'bye' n"); while(strcmp(command,"bye")){ scanf("%s",command);
  • 75. Odd sem 2023-24 Data Structure 76 if(!strcmp(command,"enter")) { scanf("%s",val); if((enqueue(&q,val)==NULL)) printf("No more pushing please n"); else printf("Name entered %s n",val); } if(!strcmp(command,"delete")) { if(!isEmpty(&q)) printf("%s n",dequeue(&q,val)); else printf("Name deleted %s n",val); } } /* while */ printf("End session n"); }
  • 76. Problem With Array Implementation Odd sem 2023-24 Data Structure 77 front rear rear ENQUEUE front DEQUEUE Effective queuing storage area of array gets reduced. Use of circular array indexing 0 N
  • 77. Queue: Example with Array Implementation Odd sem 2023-24 Data Structure 78 typedef struct { char name[30]; } _ELEMENT; typedef struct { _ELEMENT q_elem[MAX_SIZE]; int rear; int front; int full,empty; } _QUEUE; #define MAX_SIZE 100
  • 78. Queue Example: Contd. Odd sem 2023-24 Data Structure 79 void init_queue(_QUEUE *q) {q->rear= q->front= 0; q->full=0; q->empty=1; } int IsFull(_QUEUE *q) {return(q->full);} int IsEmpty(_QUEUE *q) {return(q->empty);}
  • 79. Queue Example: Contd. Odd sem 2023-24 Data Structure 80 void AddQ(_QUEUE *q, _ELEMENT ob) { if(IsFull(q)) {printf("Queue is Full n"); return;} q->rear=(q->rear+1)%(MAX_SIZE); q->q_elem[q->rear]=ob; if(q->front==q->rear) q->full=1; else q->full=0; q->empty=0; return; }
  • 80. Queue Example: Contd. Odd sem 2023-24 Data Structure 81 _ELEMENT DeleteQ(_QUEUE *q) { _ELEMENT temp; temp.name[0]='0'; if(IsEmpty(q)) {printf("Queue is EMPTYn");return(temp);} q->front=(q->front+1)%(MAX_SIZE); temp=q->q_elem[q->front]; if(q->rear==q->front) q->empty=1; else q->empty=0; q->full=0; return(temp); }
  • 81. Queue Example: Contd. Odd sem 2023-24 Data Structure 82 main() { int i,j; char command[5]; _ELEMENT ob; _QUEUE A; init_queue(&A); command[0]='0'; printf("For adding a name use 'add [name]'n"); printf("For deleting use 'delete' n"); printf("To end the session use 'bye' n"); #include <stdio.h> #include <stdlib.h> #include <string.h>
  • 82. Queue Example: Contd. Odd sem 2023-24 Data Structure 83 while (strcmp(command,"bye")!=0){ scanf("%s",command); if(strcmp(command,"add")==0) { scanf("%s",ob.name); if (IsFull(&A)) printf("No more insertion please n"); else { AddQ(&A,ob); printf("Name inserted %s n",ob.name); } }
  • 83. Queue Example: Contd. Odd sem 2023-24 Data Structure 84 if (strcmp(command,"delete")==0) { if (IsEmpty(&A)) printf("Queue is empty n"); else { ob=DeleteQ(&A); printf("Name deleted %s n",ob.name); } } } /* End of while */ printf("End session n"); }