0% found this document useful (0 votes)
29 views112 pages

Linkedlist

This document provides information about linked lists, including: - Linked lists are collections of nodes where each node contains data and a pointer to the next node. - Linked lists can be linear, circular, doubly linked, or have a header node. - The document describes how to implement linked lists in C using structures containing data and pointer fields. - Operations like insertion and deletion at different positions in the linked list are demonstrated through code examples. - Applications like representing polynomials with linked lists are discussed.

Uploaded by

Shalini Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views112 pages

Linkedlist

This document provides information about linked lists, including: - Linked lists are collections of nodes where each node contains data and a pointer to the next node. - Linked lists can be linear, circular, doubly linked, or have a header node. - The document describes how to implement linked lists in C using structures containing data and pointer fields. - Operations like insertion and deletion at different positions in the linked list are demonstrated through code examples. - Applications like representing polynomials with linked lists are discussed.

Uploaded by

Shalini Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 112

Linked List

Programming and Data Structure 1


• Liked List
• A Linked List is a order collection of finite Homogenous data
elements or Nodes, where the linear order is maintained by link or
pointer.
• Each Node has two part-
• Info part :- First part contains the information of the node.
• Link:- Second part contains the address of the next node.

Info Link

Spring 2012 Programming and Data Structure 2


 
Types of Linked List:-
Linked List are classified into following categories:-
Linear Linked List:- In linear linked list each node is divided into two parts. First part
store the information of the node and second part store the address of the next
Node in the list and Null pointer represent that there are no more nodes in the
linked list.

1005 2000 3005


40 Null
10 1005 20 2000 30 3005

Spring 2012 Programming and Data Structure 3


• (ii) Circular Linked List:- In this linked list
second part of the last node contains the
address of first node then it is called circular
linked list.

Spring 2012 Programming and Data Structure 4


• (iii) Header Linked List:- Header linked list
always contain a header node at the
beginning of the link list. This Node is known
as header Node which stores the address of
first node.

Spring 2012 Programming and Data Structure 5


• Doubly -Linked List:- It is also known as Tow-way list in this
type of list each node contain three part, predecessor part,
successor part, info part.
• In Doubly link list we can access both the successor &
predecessor nodes.

Programming and Data Structure 6


• Circular Doubly -Linked List:- A circular doubly
link list is one which has both successor &
predecessor pointer in circular Manner.
1000

Spring 2012 Programming and Data Structure 7


• struct node
• {
• int info;
• struct node *link;
• };

• Struct node *top;


• Void create()
• { struct node *ptr,*cpt;
• Char ch;

• ptr = (struct node*)malloc (size of (struct node));


• printf(“input first node information”);
• scanf(“%d”, &ptr →info);
• Ptr->link=Null;
• do
• {
cpt = (struct node*)malloc (size of (struct node));
• printf(“input next node information”);
•Spring 2012 scanf(“%d”, &cpt→info Programming
); and Data Structure 8
• ptr=3000 ptr = 5000 ptr = 8000
10 5000 20 8000 30 3000

Spring 2012 Programming and Data Structure 9


• cpt→link = ptr;
• ptr = cpt;
printf (“press y/n for more node”);
ch = getch(); ch=y
• }
• while(ch == “y”);
• top=ptr;
• }
• traverse::
• ptr = first;
• while (ptr!=NUll)
• {
• printf(“%d”, ptr→info); 10 20 30
• ptr = ptr→link;
• }

Spring 2012 Programming and Data Structure 10


• Overflow Condition: Overflow happens at the
time of insertion. If we have to insert new
datsa into the data structure, but there is no
free space, then this situation is called
overflow .
• Underflow Condition: Underflow happens at
the time of deletion. If we have to delete data
from the data structure, but there is no data
in the data structure , then this situation is
called Underflow .

Spring 2012 Programming and Data Structure 11
Insertion in a Linked list

• To insert a new node in the existing link


list.The insertion can be possible at following
any position
• At the beginning
• At the End
• At after given information node.

Spring 2012 Programming and Data Structure 12


Insertion at the end

ptr

Spring 2012 Programming and Data Structure 13


• Void insert_beg()
• {
• Struct node *ptr;
• Ptr=(struct node*)malloc(sizeof(struct node));
• If(ptr==null)
• {
• printf(“Overflow”);
• Return;
• }
• Printf(“Enter new node information”);
• Scanf(“%d”,&ptr->info);
• Ptr->link=first;
• First=ptr;
• }
Spring 2012 Programming and Data Structure 14
• Void insert_end()
• {
• Struct node *ptr;
• Ptr=(struct node*)malloc(sizeof(struct node));
• If(ptr==null)
• {
• printf(“Overflow”);
• Return;
• }
• Printf(“Enter new node information”);
• Scanf(“%d”,&ptr->info);
• Cpt=first;
• While(cpt->link!=null)
• {
• Cpt=cpt->link;
• }
• Cpt->link=ptr;
• Ptr->link=null;

• }
Spring 2012 Programming and Data Structure 15
Spring 2012 Programming and Data Structure 16
• Void insert_given_info()
• {
• Struct node *ptr;
• Int data;
• Ptr=(struct node*)malloc(sizeof(struct node));
• If(ptr==null)
• {
• printf(“Overflow”);
• Return;
• }
• Printf(“Enter new node information”);
• Scanf(“%d”,&ptr->info);
• Printf(“input information of node after want to insert”);
• Scanf(“%d”&data);
• Cpt=first;
• While(cpt->info!=data)
• {
• Cpt=cpt->link;
• }
• Ptr->link=Cpt->link;
• cpt->link=ptr;
• }
Spring 2012 Programming and Data Structure 17
• To delete the node from the existing linked list
before we have to check the underflow
condition.
• Like insertion ,deletion is also possible from
following 3 position.
• From the beginning
• From the end
• If information of node is given

Spring 2012 Programming and Data Structure 18


• Void delete_beg()
• {
• Struct node *ptr();
• If(first==NULL)
• {printf(“Underflow “);
• Return;}
• Ptr=first;
• First=ptr->link;
• Free(ptr)
• }
Spring 2012 Programming and Data Structure 19
• Void delete_end()
• {
• Struct node *ptr();
• If(first==NULL)
• {printf(“Underflow “);
• Return;
• }
• Ptr=first;
• While(ptr->link!=NULL)
• {
• cpt=ptr;
• Ptr=ptr->link;}
• Cpt->link=NULL;
• Free(ptr);
• }
Spring 2012 Programming and Data Structure 20
• Void delete_given_info()
• {
• Struct node *ptr();
• If(first==NULL)
• {printf(“Underflow “);
• Return;
• }
• Ptr=first;
• Printf(“input information of node to be deleted”);
• Scanf(“%d”,&data);
• While(ptr->info!=data)
• {
• cpt=ptr;
• Ptr=ptr->link;
• }
• Cpt->link=ptr->link;
• Free(ptr);
• }

Spring 2012 Programming and Data Structure 21


Polynomials:
• Polynomials and Sparse Matrix are two important applications of arrays
and linked lists. A polynomial is composed of different terms where each
of them holds a coefficient and an exponent.
• A polynomial p(x) is the expression in variable x which is in the form
• (axn + bxn-1 + …. + jx+ k), where a, b, c …., k fall in the category of real
numbers and 'n' is non negative integer, which is called the degree of
polynomial.
• An essential characteristic of the polynomial is that each term in the
polynomial expression consists of two parts:
• one is the coefficient
• other is the exponent
Example:
10x2 + 26x, here 10 and 26 are coefficients and 2, 1 is its exponential value.

Spring 2012 Programming and Data Structure 22


• Points to keep in Mind while working with Polynomials:
• The sign of each coefficient and exponent is stored within the
coefficient and the exponent itself
• Additional terms having equal exponent is possible one
• The storage allocation for each term in the polynomial must
be done in ascending and descending order of their exponent

Spring 2012 Programming and Data Structure 23



Polynomial can be represented in the various
ways. These are:
• By the use of arrays
• By the use of Linked List

Spring 2012 Programming and Data Structure 24


• struct node
• {
• int coff;
• Int expo;
• struct node *link;
• };

• Struct node *first, *cpt, *ptr;

• ptr = (struct node*)malloc (size of (struct node));


• printf(“input first term coefficient and exponent”);
• scanf(“%d”, &ptr →coff,&ptr->expo);
• first = ptr;
• do
• {
cpt = (struct node*)malloc (size of (struct node));
• printf(“input next term”);
• scanf(“%d”, &cpt→coff,&cpt->expo );

Spring 2012 Programming and Data Structure 25


• ptr→link = cpt;
• ptr = cpt;

• printf (“press y/n for more node”);


ch = getch(); ch=y
• }
• while(ch == “y”);
• ptr→link=NULL;
• }
• traverse::
• ptr = first;
• while (ptr!=first)
• {
• printf(“%d”, ptr→coff);
• Printf(“%d”,ptr->expo);
• ptr = ptr→link;
• }

Spring 2012 Programming and Data Structure 26


Spring 2012 Programming and Data Structure 27
Spring 2012 Programming and Data Structure 28
Spring 2012 Programming and Data Structure 29
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.
head
– It does not waste memory space.

A B C

Programming and Data Structure 30


Spring 2012 Programming and Data Structure 31
Spring 2012 Programming and Data Structure 32
Spring 2012 Programming and Data Structure 33
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)


head
• One we have discussed so far.

A B C

Spring 2012 Programming and Data Structure 34


– Circular linked list
• The pointer from the last element in the list points back
to the first element.
head

A B C

Spring 2012 Programming and Data Structure 35


– 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
head tail
the list, head and tail.

A B C

Spring 2012 Programming and Data Structure 36


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 37


Pseudo-code for insertion
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;
}
Spring 2012 Programming and Data Structure 38
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 39
Illustration: Deletion
Item to be deleted

A B C

tmp
curr

A B C

Spring 2012 Programming and Data Structure 40


Pseudo-code for deletion
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);
}

Spring 2012 Programming and Data Structure 41


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 42


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 43


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 44
Conceptual Idea

Insert
List
implementation
Delete
and the
related functions
Traverse

Spring 2012 Programming and Data Structure 45


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 46


Creating a List

Spring 2012 Programming and Data Structure 47


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));
head
roll
name next
age

Spring 2012 Programming and Data Structure 48


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
head formed.

A B C

Spring 2012 Programming and Data Structure 49


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 50


• To be called from main() function as:

node *head;
………
head = create_list();

Spring 2012 Programming and Data Structure 51


Traversing the List

Spring 2012 Programming and Data Structure 52


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 53


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 54


• To be called from main() function as:

node *head;
………
display (head);

Spring 2012 Programming and Data Structure 55


Inserting a Node in a List

Spring 2012 Programming and Data Structure 56


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 57


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 58


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 59


else
{
while ((p != NULL) && (p->roll != rno))

{
q = p;
p = p->next;
} The pointers
q and p
if (p == NULL) /* At the end */ always point
{ to consecutive
q->next = new; nodes.
new->next = NULL;
}
else if (p->roll == rno)
/* In the middle */
{
q->next = new;
new->next = p;
}
}
}
Spring 2012 Programming and Data Structure 60
• To be called from main() function as:

node *head;
………
insert (&head);

Spring 2012 Programming and Data Structure 61


Deleting a node from the list

Spring 2012 Programming and Data Structure 62


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 63


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 64


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);
}
}
}

Spring 2012 Programming and Data Structure 65


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 66


A First-in First-out (FIFO) List
In Out

B A
C B A

Also called a QUEUE

Spring 2012 Programming and Data Structure 67


A Last-in First-out (LIFO) List
In Out

C B A B C

Also called a
STACK

Spring 2012 Programming and Data Structure 68


Abstract Data Types

Spring 2012 Programming and Data Structure 69


Example 1 :: Complex numbers
struct cplx {
float re; Structure
float im;
definition
}
typedef struct cplx complex;

complex *add (complex a, complex b);


complex *sub (complex a, complex b);
complex *mul (complex a, complex b); Function
complex *div (complex a, complex b); prototypes
complex *read();
void print (complex a);

Spring 2012 Programming and Data Structure 70


add

sub

mul Complex
Number
div

read

print
Spring 2012 Programming and Data Structure 71
Example 2 :: Set manipulation
struct node {
int element; Structure
struct node *next;
definition
}
typedef struct node set;

set *union (set a, set b);


set *intersect (set a, set b);
set *minus (set a, set b); Function
void insert (set a, int x); prototypes
void delete (set a, int x);
int size (set a);

Spring 2012 Programming and Data Structure 72


union

intersect

minus
Set
insert

delete

size
Spring 2012 Programming and Data Structure 73
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 74


push

pop

create
STACK
isempty

isfull

Spring 2012 Programming and Data Structure 75


Contd.
• We shall look into two different ways of
implementing stack:
– Using arrays
– Using linked list

Spring 2012 Programming and Data Structure 76


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 77


enqueue

dequeue

create
QUEUE
isempty

size

Spring 2012 Programming and Data Structure 78


Stack Implementations: Using Array
and Linked List

Spring 2012 Programming and Data Structure 79


STACK USING ARRAY

PUSH

top
top

Spring 2012 Programming and Data Structure 80


STACK USING ARRAY

POP

top
top

Spring 2012 Programming and Data Structure 81


Stack: Linked List Structure

PUSH OPERATION

top

Spring 2012 Programming and Data Structure 82


Stack: Linked List Structure

POP OPERATION

top

Spring 2012 Programming and Data Structure 83


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 85


Declaration
#define MAXSIZE 100 struct lifo
{
struct lifo int value;
{ struct lifo *next;
int st[MAXSIZE]; };
int top; typedef struct lifo
}; stack;
typedef struct lifo
stack; stack *top;
stack s;

ARRAY LINKED LIST

Spring 2012 Programming and Data Structure 86


Stack Creation
void create (stack *s) void create (stack **top)
{ {
s->top = -1; *top = NULL;

/* s->top points to /* top points to NULL,


last element indicating empty
pushed in; stack */
initially -1 */ }
}
LINKED LIST
ARRAY

Spring 2012 Programming and Data Structure 87


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;
}
}

ARRAY
Spring 2012 Programming and Data Structure 88
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;
}

LINKED LIST
Spring 2012 Programming and Data Structure 89
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--]);
}
}

ARRAY

Spring 2012 Programming and Data Structure 90


int pop (stack **top)
{
int t;
stack *p;
if (*top == NULL)
{
printf (“\n Stack is empty”);
exit(-1); LINKED LIST
}
else
{
t = (*top)->value;
p = *top;
*top = (*top)->next;
free (p);
return t;
}
}

Spring 2012 Programming and Data Structure 91


Checking for stack empty
int isempty (stack *s) int isempty (stack *top)
{ {
if (s->top == -1) if (top == NULL)
return 1; return (1);
else else
return (0); return (0);
} }

ARRAY LINKED LIST

Spring 2012 Programming and Data Structure 92


Checking for stack full
int isfull (stack *s) • Not required for linked list
{ implementation.
if (s->top == • In the push() function, we
(MAXSIZE–1))
can check the return value of
return 1;
malloc().
else – If -1, then memory cannot be
return (0); allocated.
}

ARRAY LINKED LIST

Spring 2012 Programming and Data Structure 93


Example main function :: array
#include <stdio.h> push(&A,30);
#define MAXSIZE 100 push(&B,100); push(&B,5);
struct lifo printf (“%d %d”, pop(&A),
{ pop(&B));
int st[MAXSIZE];
int top; push (&A, pop(&B));
}; if (isempty(&B))
typedef struct lifo stack; printf (“\n B is empty”);
main() }
{
stack A, B;
create(&A); create(&B);
push(&A,10);
push(&A,20);

Spring 2012 Programming and Data Structure 94


Example main function :: linked list
#include <stdio.h> push(&A,30);
struct lifo push(&B,100);
{ push(&B,5);
int value;
printf (“%d %d”,
struct lifo *next;
pop(&A), pop(&B));
};
typedef struct lifo stack; push (&A, pop(&B));

main() if (isempty(B))
{ printf (“\n B is
stack *A, *B; empty”);
create(&A); create(&B); }
push(&A,10);
push(&A,20);

Spring 2012 Programming and Data Structure 95


Queue Implementation using Linked
List

Spring 2012 Programming and Data Structure 96


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 Rear
new elements will be inserted).

Front DELETION INSERTION


Spring 2012 Programming and Data Structure 97
QUEUE: LINKED LIST STRUCTURE

ENQUEUE

front rear

Spring 2012 Programming and Data Structure 98


QUEUE: LINKED LIST STRUCTURE

DEQUEUE

front rear

Spring 2012 Programming and Data Structure 99


QUEUE using Linked List
#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 100


_QNODE *enqueue (_QUEUE *q, char x[])
{
if(q->queue_rear==NULL)
_QNODE *temp;
{
temp= (_QNODE *)
q->queue_rear=temp;
malloc (sizeof(_QNODE));
q->queue_front=
if (temp==NULL){
q->queue_rear;
printf(“Bad allocation \n");
}
return NULL;
else
}
{
strcpy(temp->name,x);
q->queue_rear->next=temp;
temp->next=NULL;
q->queue_rear=temp;
}
return(q->queue_rear);
}
Spring 2012 Programming and Data Structure 101
char *dequeue(_QUEUE *q,char x[])
{ else{
_QNODE *temp_pnt; strcpy(x,q->queue_front->name);
temp_pnt=q->queue_front;
if(q->queue_front==NULL){ q->queue_front=
q->queue_rear=NULL; q->queue_front->next;
printf("Queue is empty \n"); free(temp_pnt);
return(NULL); if(q->queue_front==NULL)
} q->queue_rear=NULL;
return(x);
}
}

Spring 2012 Programming and Data Structure 102


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 103


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 104


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");
}
Spring 2012 Programming and Data Structure 105
Problem With Array Implementation

ENQUEUE DEQUEUE

Effective queuing storage area of array gets reduced.

0 N

front
front rearrear

Use of circular array indexing


Spring 2012 Programming and Data Structure 106
Queue: Example with Array Implementation
#define MAX_SIZE 100

typedef struct { char name[30];


} _ELEMENT;

typedef struct {
_ELEMENT q_elem[MAX_SIZE];
int rear;
int front;
int full,empty;
} _QUEUE;

Spring 2012 Programming and Data Structure 107


Queue Example: Contd.
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);}

Spring 2012 Programming and Data Structure 108


Queue Example: Contd.
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;
}

Spring 2012 Programming and Data Structure 109


Queue Example: Contd.
_ELEMENT DeleteQ(_QUEUE *q)
{
_ELEMENT temp;
temp.name[0]='\0';

if(IsEmpty(q)) {printf("Queue is EMPTY\n");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);
}
Spring 2012 Programming and Data Structure 110
Queue Example: Contd.
main() #include <stdio.h>
{ #include <stdlib.h>
int i,j; #include <string.h>
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");
Spring 2012 Programming and Data Structure 111
Queue Example: Contd.
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);
}
}

Spring 2012 Programming and Data Structure 112


Queue Example: Contd.
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");
}

Spring 2012 Programming and Data Structure 113

You might also like