+ All Categories
Home > Documents > Unit 2 dsuc

Unit 2 dsuc

Date post: 09-Apr-2015
Category:
Upload: abhay-goswami
View: 151 times
Download: 1 times
Share this document with a friend
64
Unit 2 Linked List According to NIST(National Institute of Standards and Technology) linked list is “a list implemented by each item having a link to the next item”. Linked list and arrays are similar since they both store collections of data. The specific type of element is not important since essentially the same structure works to store elements of any type. A linked list is an ordered collection of data in which each element contains the location of the next element; that is, each element two parts: data and link. The data part holds the useful information, the data to be processed. The link is used, to chain the data together. It contains a pointer that identifies the next element in list. There is also a pointer variable that identifies the first element in the list.
Transcript
Page 1: Unit 2 dsuc

Unit 2Linked List

• According to NIST(National Institute of Standards and Technology) linked list is “a list implemented by each item having a link to the next item”.

• Linked list and arrays are similar since they both store collections of data.

• The specific type of element is not important since essentially the same structure works to store elements of any type.

• A linked list is an ordered collection of data in which each element contains the location of the next element; that is, each element two parts: data and link.

• The data part holds the useful information, the data to be processed.

• The link is used, to chain the data together. It contains a pointer that identifies the next element in list.

• There is also a pointer variable that identifies the first element in the list.

Page 2: Unit 2 dsuc

• The simple linked list we have described here is commonly known as a singly linked list because it contains only one link to a single successor.

• The major advantage of the linked list over other general list structures is that data are easily inserted and deleted.

• It is not necessary to shift elements of a linked list to make room for a new element or to delete an element.

• On the other hand, because the elements are no longer physically sequenced, we are limited to sequential searches; we cannot use a binary search.

• The link in each element, except the last, points to its successor.• The link in the last element contains a null pointer, indicating the

end of the list.• The elements in a linked list are traditionally called nodes.• A node in linked list is a structure that has at least two fields one

contains the data, the other a pointer to the address of the next node in the sequence.

A link List with a head pointerHead

Data Link Data Link Data Link Data LinkAn emptylist

Page 3: Unit 2 dsuc

Types of Linked Lists1. Singly-linked List:

The simplest kind of linked list is a singly-linked list, which has one link per node. This link points to next node in the list, or to null value or empty list if it is the final node.

2. Doubly-linked list:

A more sophisticated kind of linked list is a doubly-linked list or two-way linked list.

Each node has two links: one points to the previous node, or points to a null value or empty list if it is the first node; and one points to the next, or points to a null value or empty list if it is the final node.

12 99 37

A singly linked list containing three integer value

Head*prev Data *next tail

Page 4: Unit 2 dsuc

3. Circularly-linked list:

In a circularly-linked list, the first and final nodes are linked together.This can be done for both singly and doubly linked lists.

To traverse a circular linked list, you begin at any node and follow the list in either direction until you return to the original node.

(a) Singly-circularly-linked list:

In a singly-circularly-linked list, each node has one link, similar to an ordinary singly-linked list, except that the next link of the last node points back to the first node. As in a singly-linked list, new nodes can only be efficiently inserted after a node we already have a reference to.

Head

Page 5: Unit 2 dsuc

(b) Doubly-circularly-linked list:

In a doubly-circularly-linked list, each node has two links, similarly to a doubly-linked list, except that the previous link of the first node points to the last node and the next link of the last node points to first node. In a doubly-linked lists, insertions and removals can be done at any point with access to any nearby node.

Head

Page 6: Unit 2 dsuc

4. Head Linked Lists:• A headed list is linked list, which always contain a special node,

called header node, at the beginning of the linked list. This header node usually contains vital information about the linked list such as the number of nodes in the list, whether the list is sorted or not.

head Header node

Header linear linked list, also known as grounded header list

HeadHeader node

Circular header list

Page 7: Unit 2 dsuc

Head

Head

Header node

Header node

Two-way header list

Two-way circular header list

Page 8: Unit 2 dsuc

Linked List Vs. Arrays

Linked lists have several advantages over arrays.

1. Elements can be inserted into linked lists indefinitely, while an array will eventually either fill up or need to be resized, an expensive operation that may not even be possible if memory is fragmented. Similarly, an array from which many elements are removed may become wastefully empty or need to be made smaller.

2. Arrays allow random access, while linked lists allow only sequential access to elements.

3. Singly-linked lists, in fact, can only be traversed in one direction.

4. Sequential access on arrays is also faster than on linked lists on many machines.

Page 9: Unit 2 dsuc

Representation and Implementation of Singly Linked Lists:

Linked list types: Before writing the code to build the above list, we need two data types: Node and pointer

Node:• The type for the node which will make up the body of the list. • Each node contains a single client data element and a pointer to the

next node in the list. Type: struct node typedef struct node { int data; struct node* next; }node;• The type for pointers to nodes. This will be the type of the Head

pointer and the next fields inside each node. In C and C++, no separate type declaration is required since the pointer type is just the node type followed by a ‘ * ’. Type: struct node*

Page 10: Unit 2 dsuc

Dynamic Memory Management

Dynamic Memory Allocation with malloc( ) function• The malloc( ) function dynamically allocates memory . The prototype for

malloc( ) function is

void *malloc (size_t size);

It takes one argument that specifies the size of the block in bytes. The function returns a pointer to the allocated memory on success or a null pointer(0) in case of failure.

Function Name Description

Malloc Allocates memory from heap

Calloc Allocates memory and initializes the allocated memory to zero

Realloc Readjust the existing block and copies the contents to the new location

free Deallocates a block allocated by malloc,calloc and realloc fn

Page 11: Unit 2 dsuc

• Dynamic Memory Allocation with calloc( ) Function• The calloc( ) function dynamically allocates memory and

automatically initializes the memory to zeros. The prototypes for calloc( ) function is

void *calloc(size_t nitems, size_t size);

It takes two arguments. The first argument is the number of elements and the second argument is size of each element. The function returns a pointer to the allocated memory on success or a null pointer (0) in case of failure.

• Changing Size of Dynamically Allocated Memory with realloc( ) function

• The realloc( ) function changes the size of previously dynamically allocated memory with malloc ( ), calloc( ) or realloc( ) functions. The original contents held in the previously allocated memory are not changed provided the memory allocated is larger than the amount of memory previously allocated otherwise the contents are unchanged upto the size of new object. The prototype for realloc( ) fn

void *realloc( void *block, size_t size);

It takes two arguments. The first argument is the pointer to the original object and the second argument is new size of the object.

Page 12: Unit 2 dsuc

• Deallocating Memory with free( ) function

The free( ) function deallocates a memory block previously allocated with malloc( ), calloc( ) or realloc( ) functions.The prototype for free()

function is void free(void *block);

It takes one argument that specifies the pointer to the allocated block. But it is important to note that only the allocated block is deallocated, the pointer variable is not deleted.

Once the block is freed, an attempt to dereference a pointer variable yield undefined result. Such a pointer variable is called a dangling pointer. Therefore, it is recommended that after freeing the allocated block, set the pointer variable to NULL explicitly.

Page 13: Unit 2 dsuc

Algorithm for traversing a Linked List

Let LIST be a linked list in memory.This algorithm traverse LIST,applying an operation PROCESS to each element of LIST.The variable PTR points to the node currently being processed.

1 Set PTR:=START2. Repeat steps 3 and 4 while PTR!=NULL3. Apply PROCESS to INFO[PTR]4. Set PTR:=LINK[PTR] [PTR now points to next node] [End of step 2 loop]5. Exit.

Page 14: Unit 2 dsuc

Algorithm for searching a Linked List

Search(INFO,LINK,START,ITEM,LOC)

This algorithm finds location LOC of the node where ITEM first appears in LIST,or sets LOC=NULL

1. Set PTR:=START

2. Repeat step 3 while PTR!=NULL

3. If ITEM=INFO[PTR],then

Set LOC:=PTR, and exit

Else:

Set PTR:=LINK[PTR]

[End of if structure]

4. [Search is unsuccessful] Set LOC:=NULL

5.Exit

Page 15: Unit 2 dsuc

Memory Allocation

• The maintanence of linked list in memory assumes possibility of inserting new nodes into the lists and so it requires some mechanism which provide unused memory space for the new node.Also some mechanism is required so that the memory space of deleted nodes becomes available for future use.

• So along with the linked list in memory,a special list is maintained which consists of unused memory cells.

• This list which has its own pointer,is called the list of available space or the free storage list or the

free pool.

Page 16: Unit 2 dsuc

Garbage Collection

If a node is deleted from the list or the entire list is deleted from the main program.Then we want that the memory space should become reusable.To make the space available for future use, there are two ways:

1. One way is to immediately insert the list into the free storage list.This method is implemented while using linked list by means of linear arrays.But this is a time consuming process for the operating system of a computer.

2. The other method is that the OS may periodically collect all the deleted space onto the free storage list.The techinque which does this collection is called the Garbage Collection.

Page 17: Unit 2 dsuc

• Garbage Collection usually take place in two steps:

1. First the computer runs through all the lists,tagging those cells which are currently in use.

2. Then the computer runs through the memory,collecting all untagged spaces onto the free storage list.

Garbage Collection may take place when there is only some minimum amount of space or no space at all left in the free storage list,or when the CPU is idle and has time to do the collection.

It is invisible to the programmer.

Page 18: Unit 2 dsuc

Algoritm for inserting a node at the beginning of the list

INSFIRST(INFO,LINK,START,AVAIL,ITEM)

1. [OVERFLOW? ]If AVAIL=NULL,then:

Write: OVERFLOW and Exit.

2. [Remove first node from the AVAIL list]

Set NEW:=AVAIL and AVAIL:=LINK[AVAIL]

3. Set INFO[NEW]:=ITEM

4. Set LINK[NEW]:=START

5. Set START:=NEW

6. Exit.

Page 19: Unit 2 dsuc

Algorithm for inserting a node after a given node

INSLOC(INFO,LINK,START,AVAIL,LOC,ITEM) This algorithm inserts ITEM so that ITEM follows the node with

location LOC or inserts ITEM as the first node when LOC=NULL

1.[OVERFLOW?] If AVAIL=NULL,then: Write:OVERFLOW and exit2.Set NEW:=AVAIL and AVAIL:=LINK[AVAIL]3.Set INFO[NEW]:=ITEM4.If LOC=NULL,then: Set LINK[NEW]:=START and START:=NEWElse: Set LINK[NEW]:=LINK[LOC] and LINK[LOC]:=NEW [End of Ifstructure]5.Exit

Page 20: Unit 2 dsuc

Algorithm for deleting a node following a given node

DEL(INFO,LINK,START,AVAIL,LOC,LOCP)

This algorithm deletes the node N with location LOC. LOCP is the location of the node which precedes N or, when N is the first node,LOCP=NULL

1. If LOCP=NULL,then:

Set START:=LINK[START]

else:

Set LINK[LOCP]:=LINK[LOC]

[End of if structure]

2. [return deleted node to the AVAIL list]

Set LINK[LOC]:=AVAIL and AVAIL:=LOC

3.Exit.

Page 21: Unit 2 dsuc

• Creating a node:• Creating a new node is simple. The memory needed to store the node is

allocated, and the pointers are set up.

• node *create( )• { int item; node ptr;• printf("enter the item");• scanf("%d",&item);• ptr= (node *)malloc(sizeof(node));• ptr->info=item;• ptr->next=NULL;• return ptr; }• Traversing a list:• void traverseInOrder()• { node *loc;• loc=head;• while(ptr!=NULL){• printf("%d\n",loc->info);• loc=loc->next; }• }

Page 22: Unit 2 dsuc

• #include<stdio.h>• #include<conio.h>• typedef struct nodetype{• int info;• struct nodetype *next;• }node;• node *head=NULL;• node *create();• void traverseInOrder();• void main()• { node *ptr,loc;• int item; char ch;• clrscr();• do{• ptr = create();• if(head==NULL)• head=ptr;• else• {loc=head;• while(loc->next!=NULL)• loc=loc->next;• loc->next=ptr; }

Node *create( )

{ int item;

node ptr;

printf("enter the item");

scanf("%d",&item);

ptr= (node *)malloc(sizeof(node));

ptr->info=item;

ptr->next=NULL;

return ptr;

}

Page 23: Unit 2 dsuc

• printf("do you want to add one more node in the list(Y/N)");• fflush(stdin);• scanf("%c",&ch);• }while(ch=='Y'||ch=='y');• printf("the list is\n");• traverseInOrder();• getch();• }

void traverseInOrder(){ node *loc; loc=head; while(loc!=NULL){ printf("%d\n",loc->info); loc=loc->next; } }

Page 24: Unit 2 dsuc

• Inserting an element:• At the beginning of the list• At the end of the list• After a given element

• Inserting at the Beginning of the list:• void insertAtBeg(int item)• { node *ptr;• ptr=(node *)malloc(sizeof(node));• ptr->info=item;• if(head==NULL)• ptr->next=NULL;• else• ptr->next=head;• head=ptr;}

Page 25: Unit 2 dsuc

• Inserting at the end of the list:• void insertAtEnd(int item)• { node *ptr,*loc;• ptr=(node *)malloc(sizeof(node));• ptr->info=item;• ptr->next=NULL;• if(head==NULL)• head=ptr;• else{• loc=head;• while(loc->next!=NULL)• loc=loc->next;• loc->next=ptr;} }

Page 26: Unit 2 dsuc

• Inserting after the given element of the list:• void insertAfterElement(int item,int after)• {• node *ptr,*loc;• loc=searchInUnsortedList(after);• if(loc==(node*)NULL)• return;• ptr=(node*)malloc(sizeof(node));• ptr->info=item;• ptr->next=loc->next;• loc->next=ptr;• }

node *searchInUnsortedList(int item){ node *loc; loc=head; while((loc!=NULL)&&(loc->info!=item)) loc=loc->next; return loc;}

Page 27: Unit 2 dsuc

• Deleting an Element:• At the beginning of the list• At the end of the list• After a given element• Deleting from the Beginning of the list:• void deleteFromBeg()• { node *ptr;• if(head==NULL)• return;• else{• ptr=head;• head=(head)->next;• free(ptr); } }

Page 28: Unit 2 dsuc

• Deleting from the End of the list:• void deleteFromEnd()• { node *ptr, *loc;• if(head==NULL)• return;• else if ((head)->next==(node*)NULL)• { ptr=head;• head=NULL;• free(ptr); }• else• { loc=head;• ptr=(head)->next;• while(ptr->next!=NULL)• { loc=ptr;• ptr=ptr->next; }• loc->next=NULL;• free(ptr); } • }

Page 29: Unit 2 dsuc

• Deleting after a Given Element of the list:• void deleteAfterElement(int after)• {• node *ptr,*loc;• loc=searchInUnsortedList(after);• if(loc==(node*)NULL)• return;• ptr=loc->next;• loc->next=ptr->next;• free(ptr);• }

Page 30: Unit 2 dsuc

• Reversing a list:• void ReverseList()• {• node *previousNode,*currentNode,*nextNode;• currentNode=head;• nextNode=currentNode->next;• previousNode=NULL;• currentNode->next=NULL;• while(nextNode!=NULL)• {• previousNode=currentNode;• currentNode=nextNode;• nextNode=currentNode->next;• currentNode->next=previousNode;• }• head=currentNode;• }

Page 31: Unit 2 dsuc

• Deleting Entire list:• void deleteList()• { node *ptr;• while(*head!=NULL)• { ptr=*head;• *head=(*head)->next;• free(ptr);• }

Page 32: Unit 2 dsuc

Circular Linked List• The memory declarations for representing circular linked lists are

the same as for linear linked lists.• All operation performed on linear linked lists can be easily extended

for circular linked list with following exceptions:• While inserting new node at the end of the list, its next pointer field

is made to point to the first node.• While testing for end of the lists, we compare the next pointer field

with the address of the first node.

head

Circular Linked list with 4 nodes

Page 33: Unit 2 dsuc

APPLICATIONS OF LINKED LIST• To implement other data structure such as stacks, queues, trees

and graphs• To maintain a directory of names.• To manipulate polynomials.• To represent sparse matrices.

• Polynomial Manipulation• 4x3 + 6x2 + 10x + 6

Poly

Coefficient of the term power of x Linked to next node

4 3 6 2 10 1 6 0

Coefficient

Power

Representation of a polynomial

Structure of a node to represent a polynomial term

Page 34: Unit 2 dsuc

• Typedef struct nodetype• { int coeff;• int power;• struct nodetype *next;• } node;• node *poly1, *poly2,*poly3;

• Addition of Polynomials• 5x4 + 6x2 + 10x – 6• + 7x3 + 3x2 + 2x + 7• 5x4 + 7x3 + 9x2 + 12x + 1

Page 35: Unit 2 dsuc

• void addNode(node ptr, int coef, int powe)• { node *tempPtr, *loc;• tempPtr = (node *) malloc( sizeof (node));• tempPtr->coeff = coef;• tempPtr->power = powe;• tempPtr->next=NULL;• if( ptr==NULL)• ptr= tempPtr;• else• loc = ptr;• while(loc->next!= NULL)• loc=loc->next;• loc->next = tempPtr;• }

Page 36: Unit 2 dsuc

• void printPolynomial(node ptr )• { if( ptr != NULL )• printf(“%dx^%d”,ptr->coeff, ptr->power);• for(ptr= ptr->next; ptr!=NULL; ptr= ptr->next )• { • if(ptr->coeff > 0)• printf(“ + “);• if(ptr->power == 0)• printf(“%d”, ptr->coeff);• else if(ptr-> power == 1 )• printf(“%dx”, ptr-> coeff);• else• printf(“%dx^%d”, ptr->coeff, ptr->power);• } }

Page 37: Unit 2 dsuc

• void addPolynomial(node ptr1, node ptr2, node ptr3)• { int powe;• float coef;• while( ( ptr1!= NULL) && ( ptr2!=NULL) )• {• if( ptr1->power > ptr2->power ) {• coef = ptr1->coeff;• powe = ptr1->power;• ptr1 = ptr1->next; }• else if ( ptr1->power < ptr2->power) {• coef = ptr2->coeff;• powe = ptr2->power;• ptr2 = ptr2-> next; }• else {• coef = ptr1->coeff + ptr2->coeff;• powe = ptr1->power;• ptr1 = ptr1->next;• ptr2 = ptr2->next; }• if ( coef != 0 )• addnode(ptr3, coef, pow );• }

Page 38: Unit 2 dsuc

• if ( ptr1 == NULL ) {• for( ; ptr2 != NULL; ptr2= ptr2->next )• addnode( ptr3, ptr2->coeff, ptr2->power ); }• else if ( ptr2 == NULL ) {• for( ; ptr1 != NULL; ptr1 = ptr1->next )• addnode( ptr3, ptr1-> coeff, ptr1->power); }• } }• • void deletePolynomial( node ptr )• { node *temp;• while ( *ptr != NULL )• { temp = *ptr;• *ptr = (*ptr)->next;• free(temp);• }• }

Page 39: Unit 2 dsuc

Multiplication of polynomials

• 5x4 + 6x2 + 10x - 6• x 3x2 + 2x + 7• 15x6 +18x4 +30x3 -18x2

• 10x5 +12x3 +20x2 -12x• 35x4 +42x2 +70x -42• 15x6 +10x5 +53x4 +42x3 +44x2 +58x -42

Page 40: Unit 2 dsuc

• Void multiplyPolynomial( node ptr1, node ptr2, node ptr3)• {• int powe, coef ;• node *temp,*loc;• while(ptr1!=NULL)• { temp = ptr2;• while(temp !=NULL)• { coef = ptr1-> coeff * temp -> coeff;• powe = ptr1 -> power + temp -> power;• loc = search(ptr3 , powe);• if( loc == NULL)• insertNode( ptr3, coef, powe);• else • loc -> coeff += coef;• temp = temp -> next;• } ptr1 = ptr1 -> next;• } }•

Node *search( node ptr, int degree) { while ( ptr != NULL) { if ( ptr -> power == degree ) break; ptr = ptr -> next; } return ptr; }

Page 41: Unit 2 dsuc

• void InsertNode ( node ptr, int coef, int powe )• { node *tempPtr, *loc, *ploc ;• tempPtr = ( node *) malloc (sizeof (node));• tempPtr -> coeff = coef;• tempPtr -> power = powe;• if( ptr == NULL )• { tempPtr -> next = NULL;• ptr = tempPtr ; }• else {• ploc = NULL;• loc = ptr;• while( ( loc != NULL && powe < loc -> power ) )• { ploc = loc;• loc = loc -> next; }• tempPtr -> next = ploc -> next;• ploc -> next = tempPtr;• }• }• •

Page 42: Unit 2 dsuc

GENERALIZED LINKED LIST

• A Generalized List, is a finite sequence of n > = 0 elements, where each element is either an atom or a list itself.

• Example: A list A=(a,(b,c),d) It is a list of three elements.

• First and third element are atomic • Second element (b,c) is a list.

Liked Representation

1. Each node of a linked list can either be a head node or a data node.

Flag Data Next link

Page 43: Unit 2 dsuc

2. When flag=0 , the node is a data node.

3. When flag=1 ,the node is a head node.

Example: Give representation of the Generalized List

A=(1,2,(3,(4,5)),6)

0 1 0 2 1 0 6 X

0 3 1 X

0 4 0 5 X

Page 44: Unit 2 dsuc

Queues• A queue is a linear list in which insertions can take place at one

end of the list, called the rear of the list, and delete can take place only at other end, called the front of the list.

• The behaviour of a queue is like a First-In-First-Out (FIFO) system.

Operations On Queues• CreateQueue( )- to create q as an empty queue.• Enque(i)- to insert(add) element i in a queue q.• Dequeue( )- to access and remove an element of queue q.• Peek( )- to access the first element of the queue q without removing

it.• isFull( )- to check whether the queue q is full.• isEmpty( )- to check whether the queue q is empty.

Page 45: Unit 2 dsuc

-1

0

2

2

2

-1

4

4

7

9

5 7 12 8 9

12 8 9

12 8 9 3 10 11

12 8 9 3 10 11 15 20

0 8 12 8 9 3 10 11 15 20 60

Front Rear

Front Rear

Front Rear

Front Rear

Front Rear

Front Rear

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

Representation of queue in memory

Representation of queue in memory

Representation of queue in memory

Representation of queue in memory

Representation of queue in memory

Representation of queue in memory

Page 46: Unit 2 dsuc

Limitations of a linear queue

If the last position of the Queue is occupied, it is not

possible to enqueue any more elements even though some position are vacant towards the front positions of the queue.

This limitation can be overcome if we treat that the queue position with index 0 comes immediately after the last queue position with index MAX-1.The resulting queue is known as Circular Queue

Page 47: Unit 2 dsuc

Algorithm to insert an element in Queue

• QINSERT(QUEUE,N,FRONT,REAR,ITEM) This procedure inserts an element ITEM into a queue1. If FRONT=1 and REAR=N, or If FRONT=REAR+1,

then: Write: OVERFLOW and return2. If FRONT =NULL,then: Set FRONT:=1 and REAR:=1 else if REAR=N,then: Set REAR:=1 else: Set REAR:=REAR + 1[End of If structure]3.Set QUEUE[REAR]:=ITEM4.Return

Page 48: Unit 2 dsuc

Algorithm to delete an element fromQueue

• QDELETE(QUEUE,N,FRONT,REAR,ITEM) This procedure deletes an element from a queue and

assigns it to variable ITEM 1. If FRONT=NULL , then: Write: UNDERFLOW and return2..Set ITEM:=QUEUE[FRONT]3. If FRONT =REAR,then Set FRONT:=NULL and REAR:=NULL else if FRONT=N,then: Set FRONT:=1 else: Set FRONT:=FRONT + 1[End of If structure]4.Return

Page 49: Unit 2 dsuc

Applications of queues

• There are several algorithms that use queues to solve problems efficiently. For example, we have used queue for performing breadth-first search on a graph.

• When the job are submitted to a networked printer, they are arranged in order of arrival. Thus, essentially, jobs sent to a printer are placed on a queue.

• Virtually every real-life line (supposed to be) a queue. For example, lines at ticket counter at cinema halls, railway stations, bus stand, etc, are queues, because the service, i.e., ticket, is provided on first-come first-served basis.

Page 50: Unit 2 dsuc

Deque

A deque is a kind of queue in which element can be added or removed from at either end but not in the middle. The term deque is a contraction of the name double-ended queue.

There are two variations of a deque, which are intermediate between a deque and a queue.

These are:

1. Input-restricted deque – which allows insertions only at one end but allows deletions at both ends.

2. Ouput-restricted deque – which allows insertions at both ends but allows deletions only at one end.

Page 51: Unit 2 dsuc

Implementation Of Dequeue Using Arrays

• Movement in clock-wise direction:

1. If an element is inserted at the rear, then rear moves ahead in clock-wise direction.

2. If an element is deleted from the front,then front moves ahead in clock-wise direction.

• Movement in anti clock-wise direction:1. If an element is inserted from the front, then front

moves in anti clock-wise direction.

2. If an element is deleted from the rear, then rear moves in anti clock-wise direction.

Page 52: Unit 2 dsuc

• Expression for clockwise movement

1. Rear=(rear+1) % MAX where MAX is the size of array.

2. Front=(front+1) % MAX

• Expression for anti clockwise movement

1. Rear=(rear -1+MAX) % MAX

2. Front=(front-1+MAX) % MAX

Page 53: Unit 2 dsuc

Priority Queue

• An element with highest priority is processed first before any element of lowest priority.

• Two or more element with the same priority are processed according to the order in which they were added to the queue.

• There can be different criteria’s for determining the priority. Some of them are summarized below:

1. A shortest job is given highest priority over the longer one.

2. An important job is given the higher priority over a routine type job.

Page 54: Unit 2 dsuc

• Representation of Queues in Memory:• typedef struct• { int front, rear;• int element[capacity];• }queue; queue q;

• Typedef enum {false, true} boolean;

• Creating an empty Linear Queue:• void createQueue( )• {q.front=q.rear=-1;• }

• Testing a linear Queue for Underflow:• boolean isEmpty()• { if(q.front==-1)• return true;• else• return false; }

Page 55: Unit 2 dsuc

• Testing a linear Queue for Overflow:• boolean isFull()• { if((q.front==0)&&(q.rear==capacity-1))• return true;• else• return false; }

• Enqueue operation on linear Queue:• void enqueue(int element){• int i;• if(q.front==-1)• q.front=q.rear=0;• else if(q.rear==capacity-1)• { for(i=q.front;i<=q.rear;i++)• q.element[i-q.front]=q.element[i];• q.rear=q.rear-q.front+1;• q.front=0; } • else { q.rear++; }• q.element[q.rear]=element; }

Page 56: Unit 2 dsuc

• Dequeue operation on a linear queue:• int dequeue() {• int temp;• temp=q.element[q.front];• if(q.front==q.rear)• q.front=q.rear=-1;• else• q.front++;• return temp; }

• Accessing Front Element:• int peek(){• return q.element[q.front];• }

Page 57: Unit 2 dsuc

• #define capacity 10• typedef enum{false,true}boolean;• typedef struct• { int front, rear;• int element[capacity];• }queue; queue q;• void createQueue();• boolean isEmpty();• boolean isFull();• void enqueue(int);• int dequeue();• void main()• { int choice, element;• createQueue();• do• { clrscr();• printf("Option available\n");• printf("1. Enqueue\n");• printf("2. Dequeue\n");• printf("3. Peek\n");• printf("4. Exit\n\n");• printf("Enter choice(1-4):");• scanf("%d",&choice);

Page 58: Unit 2 dsuc

• switch(choice)• { case 1: clrscr();• if(isFull()){• printf("Queue full...\nPress any key to continue");• getch();• }else{• printf("Enter value:");• scanf("%d",&element);• enqueue(element);• }break;• case 2: clrscr();• if(isEmpty()){• printf("Queue empty...\nPress anykey to continue");• getch();• }else{• printf("Value dequeue is %d\n",dequeue());• printf("\nPress any key to continue...");• getch();• }break;•

Page 59: Unit 2 dsuc

• case 3: clrscr();• if(isEmpty()){• printf("Queue empty...\nPree any key to continue");• getch();• }else{• printf("1st Element in queue is %d\n",peek());• printf("Press any key to continue...");• getch();• }• }• }while(choice!=4);• getch();• }

Page 60: Unit 2 dsuc

• Enqueue Operation on a circular Queue:• void enqueue(int element){• int i;• if(q.front==-1)• q.front=q.rear=0;• else if(q.rear==capacity-1)• q.rear=0;• else• q.rear++;• q.element[q.rear]=element; }

• void enqueue(int element){• int i;• if(q.front==-1)• q.front=q.rear=0;• else• q.rear=(q.rear+1)%capacity;• q.element[q.rear]=element; }

Page 61: Unit 2 dsuc

• Dequeue operation on a circular Queue:• int dequeue() {• int temp;• temp=q.element[q.front];• if(q.front==q.rear)• q.front=q.rear=-1;• else if(q.front==capacity-1)• q.front=0;• else• q.front++;• return temp; }

• int dequeue() {• int temp;• temp=q.element[q.front];• if(q.front==q.rear)• q.front=q.rear=-1;• else• q.front=(q.front+1)%capacity;• return temp; }

Page 62: Unit 2 dsuc

• #define capacity 10• typedef enum{false,true}boolean;• typedef struct• { int front, rear;• int element[capacity];• }queue; queue q;• void createQueue();• boolean isEmpty();• boolean isFull();• void enqueue(int);• int dequeue();• void main()• { int choice, element;• createQueue();• do• { • printf("1. Enqueue\n");• printf("2. Dequeue\n");• printf("3. Peek\n");• printf("4. Exit\n\n");• printf("Enter choice(1-4):");• scanf("%d",&choice);

Page 63: Unit 2 dsuc

• switch(choice)• {• case 1: clrscr();• if(isFull()){• printf("Queue full...\nPress any key to continue");• getch();• }else{• printf("Enter value:");• scanf("%d",&element);• enqueue(element);• }break;• case 2: clrscr();• if(isEmpty()){• printf("Queue empty...\nPress anykey to continue");• getch();• }else{• printf("Value dequeue is %d\n",dequeue());• printf("\nPress any key to continue...");• getch();• }break;

Page 64: Unit 2 dsuc

• case 3: clrscr();• if(isEmpty()){• printf("Queue empty...\nPree any key to continue");• getch();• }else{• printf("1st Element in queue is %d\n",peek());• printf("Press any key to continue...");• getch();• }• }• }while(choice!=4);• getch();• }


Recommended