SlideShare a Scribd company logo
1 of 82
Linked List
Spring 2012 Programming and Data Structure 1
Introduction
• 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.
Spring 2012 Programming and Data Structure 2
A B C
head
• 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.
Spring 2012 Programming and Data Structure 3
Illustration: Insertion
Spring 2012 Programming and Data Structure 4
A
A
Item to be
inserted
X
X
A B C
B C
curr
tmp
Pseudo-code for insertion
Spring 2012 Programming and Data Structure 5
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;
}
Illustration: Deletion
Spring 2012 Programming and Data Structure 6
A B
A B C
C
Item to be deleted
curr
tmp
Pseudo-code for deletion
Spring 2012 Programming and Data Structure 7
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);
}
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.
Spring 2012 Programming and Data Structure 8
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.
Spring 2012 Programming and Data Structure 9
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.
Spring 2012 Programming and Data Structure 10
A B C
head
– Circular linked list
• The pointer from the last element in the list points back
to the first element.
Spring 2012 Programming and Data Structure 11
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.
Spring 2012 Programming and Data Structure 12
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
Spring 2012 Programming and Data Structure 13
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.
Spring 2012 Programming and Data Structure 14
Conceptual Idea
Spring 2012 Programming and Data Structure 15
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;
Spring 2012 Programming and Data Structure 16
Creating a List
Spring 2012 Programming and Data Structure 17
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));
Spring 2012 Programming and Data Structure 18
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.
Spring 2012 Programming and Data Structure 19
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);
}
Spring 2012 Programming and Data Structure 20
• To be called from main() function as:
node *head;
………
head = create_list();
Spring 2012 Programming and Data Structure 21
Traversing the List
Spring 2012 Programming and Data Structure 22
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.
Spring 2012 Programming and Data Structure 23
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");
}
Spring 2012 Programming and Data Structure 24
• To be called from main() function as:
node *head;
………
display (head);
Spring 2012 Programming and Data Structure 25
Inserting a Node in a List
Spring 2012 Programming and Data Structure 26
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.
Spring 2012 Programming and Data Structure 27
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.
Spring 2012 Programming and Data Structure 28
Spring 2012 Programming and Data Structure 29
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;
}
Spring 2012 Programming and Data Structure 30
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);
Spring 2012 Programming and Data Structure 31
Deleting a node from the list
Spring 2012 Programming and Data Structure 32
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.
Spring 2012 Programming and Data Structure 33
Spring 2012 Programming and 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);
}
Spring 2012 Programming and 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);
}
}
}
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 */
Spring 2012 Programming and Data Structure 36
A First-in First-out (FIFO) List
Spring 2012 Programming and Data Structure 37
Also called a QUEUE
In Out
A
C B
A
B
A Last-in First-out (LIFO) List
Spring 2012 Programming and Data Structure 38
In Out
A
B
C C
B
Also called a
STACK
Abstract Data Types
Spring 2012 Programming and Data Structure 39
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);
Spring 2012 Programming and Data Structure 40
Structure
definition
Function
prototypes
Spring 2012 Programming and Data Structure 41
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);
Spring 2012 Programming and Data Structure 42
Structure
definition
Function
prototypes
Spring 2012 Programming and Data Structure 43
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 */
Spring 2012 Programming and Data Structure 44
Spring 2012 Programming and Data Structure 45
STACK
push
create
pop
isfull
isempty
Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list
Spring 2012 Programming and Data Structure 46
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 */
Spring 2012 Programming and Data Structure 47
Spring 2012 Programming and Data Structure 48
QUEUE
enqueue
create
dequeue
size
isempty
Stack Implementations: Using Array
and Linked List
Spring 2012 Programming and Data Structure 49
STACK USING ARRAY
Spring 2012 Programming and Data Structure 50
top
top
PUSH
STACK USING ARRAY
Spring 2012 Programming and Data Structure 51
top
top
POP
Stack: Linked List Structure
Spring 2012 Programming and Data Structure 52
top
PUSH OPERATION
Stack: Linked List Structure
Spring 2012 Programming and Data Structure 53
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.
Spring 2012 Programming and Data Structure 55
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;
Spring 2012 Programming and Data Structure 56
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 */
}
Spring 2012 Programming and Data Structure 57
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;
}
}
Spring 2012 Programming and Data Structure 58
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;
}
Spring 2012 Programming and Data Structure 59
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--]);
}
}
Spring 2012 Programming and Data Structure 60
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;
}
}
Spring 2012 Programming and Data Structure 61
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);
}
Spring 2012 Programming and Data Structure 62
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.
Spring 2012 Programming and Data Structure 63
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”);
}
Spring 2012 Programming and Data Structure 64
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”);
}
Spring 2012 Programming and Data Structure 65
Queue Implementation using Linked
List
Spring 2012 Programming and Data Structure 66
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).
Spring 2012 Programming and Data Structure 67
Front
Rear
DELETION INSERTION
QUEUE: LINKED LIST STRUCTURE
Spring 2012 Programming and Data Structure 68
front rear
ENQUEUE
QUEUE: LINKED LIST STRUCTURE
Spring 2012 Programming and Data Structure 69
front rear
DEQUEUE
QUEUE using Linked List
Spring 2012 Programming and Data Structure 70
#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;
Spring 2012 Programming and Data Structure 71
_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);
}
Spring 2012 Programming and Data Structure 72
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);
}
}
Spring 2012 Programming and Data Structure 73
void init_queue(_QUEUE *q)
{
q->queue_front= q->queue_rear=NULL;
}
int isEmpty(_QUEUE *q)
{
if(q==NULL) return 1;
else return 0;
}
Spring 2012 Programming and Data Structure 74
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);
Spring 2012 Programming and Data Structure 75
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
Spring 2012 Programming and Data Structure 76
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
Spring 2012 Programming and Data Structure 77
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.
Spring 2012 Programming and Data Structure 78
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.
Spring 2012 Programming and Data Structure 79
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.
Spring 2012 Programming and Data Structure 80
_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.
Spring 2012 Programming and Data Structure 81
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.
Spring 2012 Programming and Data Structure 82
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.
Spring 2012 Programming and Data Structure 83
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 Wk11-linkedlist.ppt

linklked lisdi.pdf
linklked lisdi.pdflinklked lisdi.pdf
linklked lisdi.pdfVinayKamriya
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.pptRahulYadav738822
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked ListsJ.T.A.JONES
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.pptmrizwan38
 
Circular linked list
Circular linked listCircular linked list
Circular linked listdchuynh
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked ListThenmozhiK5
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptxmsohail37
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 

Similar to Wk11-linkedlist.ppt (20)

linklked lisdi.pdf
linklked lisdi.pdflinklked lisdi.pdf
linklked lisdi.pdf
 
Data structures
Data structuresData structures
Data structures
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Data structure
 Data structure Data structure
Data structure
 
cs201-list-stack-queue.ppt
cs201-list-stack-queue.pptcs201-list-stack-queue.ppt
cs201-list-stack-queue.ppt
 
Sorting & Linked Lists
Sorting & Linked ListsSorting & Linked Lists
Sorting & Linked Lists
 
Adt of lists
Adt of listsAdt of lists
Adt of lists
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Linked list
Linked listLinked list
Linked list
 
Unit7 C
Unit7 CUnit7 C
Unit7 C
 
Linked list
Linked listLinked list
Linked list
 
lect- 3&4.ppt
lect- 3&4.pptlect- 3&4.ppt
lect- 3&4.ppt
 
Unit 5 linked list
Unit   5 linked listUnit   5 linked list
Unit 5 linked list
 
Circular linked list
Circular linked listCircular linked list
Circular linked list
 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
 
Savitch Ch 13
Savitch Ch 13Savitch Ch 13
Savitch Ch 13
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
DS_LinkedList.pptx
DS_LinkedList.pptxDS_LinkedList.pptx
DS_LinkedList.pptx
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 

Recently uploaded

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Wk11-linkedlist.ppt

  • 1. Linked List Spring 2012 Programming and Data Structure 1
  • 2. Introduction • 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. Spring 2012 Programming and Data Structure 2 A B C head
  • 3. • 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. Spring 2012 Programming and Data Structure 3
  • 4. Illustration: Insertion Spring 2012 Programming and Data Structure 4 A A Item to be inserted X X A B C B C curr tmp
  • 5. Pseudo-code for insertion Spring 2012 Programming and Data Structure 5 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; }
  • 6. Illustration: Deletion Spring 2012 Programming and Data Structure 6 A B A B C C Item to be deleted curr tmp
  • 7. Pseudo-code for deletion Spring 2012 Programming and Data Structure 7 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); }
  • 8. 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. Spring 2012 Programming and Data Structure 8
  • 9. 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. Spring 2012 Programming and Data Structure 9
  • 10. 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. Spring 2012 Programming and Data Structure 10 A B C head
  • 11. – Circular linked list • The pointer from the last element in the list points back to the first element. Spring 2012 Programming and Data Structure 11 A B C head
  • 12. – 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. Spring 2012 Programming and Data Structure 12 A B C head tail
  • 13. 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 Spring 2012 Programming and Data Structure 13
  • 14. 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. Spring 2012 Programming and Data Structure 14
  • 15. Conceptual Idea Spring 2012 Programming and Data Structure 15 List implementation and the related functions Insert Delete Traverse
  • 16. 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; Spring 2012 Programming and Data Structure 16
  • 17. Creating a List Spring 2012 Programming and Data Structure 17
  • 18. 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)); Spring 2012 Programming and Data Structure 18 head age name roll next
  • 19. 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. Spring 2012 Programming and Data Structure 19 A B C head
  • 20. 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); } Spring 2012 Programming and Data Structure 20
  • 21. • To be called from main() function as: node *head; ……… head = create_list(); Spring 2012 Programming and Data Structure 21
  • 22. Traversing the List Spring 2012 Programming and Data Structure 22
  • 23. 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. Spring 2012 Programming and Data Structure 23
  • 24. 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"); } Spring 2012 Programming and Data Structure 24
  • 25. • To be called from main() function as: node *head; ……… display (head); Spring 2012 Programming and Data Structure 25
  • 26. Inserting a Node in a List Spring 2012 Programming and Data Structure 26
  • 27. 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. Spring 2012 Programming and Data Structure 27
  • 28. 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. Spring 2012 Programming and Data Structure 28
  • 29. Spring 2012 Programming and Data Structure 29 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; }
  • 30. Spring 2012 Programming and Data Structure 30 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.
  • 31. • To be called from main() function as: node *head; ……… insert (&head); Spring 2012 Programming and Data Structure 31
  • 32. Deleting a node from the list Spring 2012 Programming and Data Structure 32
  • 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. Spring 2012 Programming and Data Structure 33
  • 34. Spring 2012 Programming and 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. Spring 2012 Programming and 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. 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 */ Spring 2012 Programming and Data Structure 36
  • 37. A First-in First-out (FIFO) List Spring 2012 Programming and Data Structure 37 Also called a QUEUE In Out A C B A B
  • 38. A Last-in First-out (LIFO) List Spring 2012 Programming and Data Structure 38 In Out A B C C B Also called a STACK
  • 39. Abstract Data Types Spring 2012 Programming and Data Structure 39
  • 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); Spring 2012 Programming and Data Structure 40 Structure definition Function prototypes
  • 41. Spring 2012 Programming and Data Structure 41 Complex Number add print mul sub read div
  • 42. 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); Spring 2012 Programming and Data Structure 42 Structure definition Function prototypes
  • 43. Spring 2012 Programming and Data Structure 43 Set union size minus intersect delete insert
  • 44. 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 */ Spring 2012 Programming and Data Structure 44
  • 45. Spring 2012 Programming and Data Structure 45 STACK push create pop isfull isempty
  • 46. Contd. • We shall look into two different ways of implementing stack: – Using arrays – Using linked list Spring 2012 Programming and Data Structure 46
  • 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 */ Spring 2012 Programming and Data Structure 47
  • 48. Spring 2012 Programming and Data Structure 48 QUEUE enqueue create dequeue size isempty
  • 49. Stack Implementations: Using Array and Linked List Spring 2012 Programming and Data Structure 49
  • 50. STACK USING ARRAY Spring 2012 Programming and Data Structure 50 top top PUSH
  • 51. STACK USING ARRAY Spring 2012 Programming and Data Structure 51 top top POP
  • 52. Stack: Linked List Structure Spring 2012 Programming and Data Structure 52 top PUSH OPERATION
  • 53. Stack: Linked List Structure Spring 2012 Programming and Data Structure 53 top POP OPERATION
  • 54. 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. Spring 2012 Programming and Data Structure 55
  • 55. 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; Spring 2012 Programming and Data Structure 56 ARRAY LINKED LIST
  • 56. 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 */ } Spring 2012 Programming and Data Structure 57 ARRAY LINKED LIST
  • 57. 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; } } Spring 2012 Programming and Data Structure 58 ARRAY
  • 58. 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; } Spring 2012 Programming and Data Structure 59 LINKED LIST
  • 59. 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--]); } } Spring 2012 Programming and Data Structure 60 ARRAY
  • 60. 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; } } Spring 2012 Programming and Data Structure 61 LINKED LIST
  • 61. 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); } Spring 2012 Programming and Data Structure 62 ARRAY LINKED LIST
  • 62. 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. Spring 2012 Programming and Data Structure 63 ARRAY LINKED LIST
  • 63. 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”); } Spring 2012 Programming and Data Structure 64
  • 64. 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”); } Spring 2012 Programming and Data Structure 65
  • 65. Queue Implementation using Linked List Spring 2012 Programming and Data Structure 66
  • 66. 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). Spring 2012 Programming and Data Structure 67 Front Rear DELETION INSERTION
  • 67. QUEUE: LINKED LIST STRUCTURE Spring 2012 Programming and Data Structure 68 front rear ENQUEUE
  • 68. QUEUE: LINKED LIST STRUCTURE Spring 2012 Programming and Data Structure 69 front rear DEQUEUE
  • 69. QUEUE using Linked List Spring 2012 Programming and Data Structure 70 #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;
  • 70. Spring 2012 Programming and Data Structure 71 _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); }
  • 71. Spring 2012 Programming and Data Structure 72 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); } }
  • 72. Spring 2012 Programming and Data Structure 73 void init_queue(_QUEUE *q) { q->queue_front= q->queue_rear=NULL; } int isEmpty(_QUEUE *q) { if(q==NULL) return 1; else return 0; }
  • 73. Spring 2012 Programming and Data Structure 74 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);
  • 74. Spring 2012 Programming and Data Structure 75 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"); }
  • 75. Problem With Array Implementation Spring 2012 Programming and Data Structure 76 front rear rear ENQUEUE front DEQUEUE Effective queuing storage area of array gets reduced. Use of circular array indexing 0 N
  • 76. Queue: Example with Array Implementation Spring 2012 Programming and Data Structure 77 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
  • 77. Queue Example: Contd. Spring 2012 Programming and Data Structure 78 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);}
  • 78. Queue Example: Contd. Spring 2012 Programming and Data Structure 79 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; }
  • 79. Queue Example: Contd. Spring 2012 Programming and Data Structure 80 _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); }
  • 80. Queue Example: Contd. Spring 2012 Programming and Data Structure 81 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>
  • 81. Queue Example: Contd. Spring 2012 Programming and Data Structure 82 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); } }
  • 82. Queue Example: Contd. Spring 2012 Programming and Data Structure 83 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"); }