LINKED LIST, STACKS AND QUEUES Saras M Srivastava, PGT – Comp. Sc. Kendriya Vidyalaya TengaValley

Preview:

Citation preview

LINKED LIST, STACKS AND QUEUES

Saras M Srivastava, PGT – Comp. Sc.

Kendriya Vidyalaya TengaValley

LINKED LIST

Singly Linked List: Contains the address of the next node.

Doubly Linked List: Contains the address of the next node as well as address of previous nodes also.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 2

OPERATIONS TO BE PERFORMED IN LINKED LIST

Insertion of Node◦ In the beginning◦ At the End of the Linked List

Deletion of the NodeTraversal of the Linked List

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 3

INSERTION OF THE NODE ( IN THE BEGINNING)

Algorithm

1.Ptr = start

2.newptr = new node

3.If newptr = NULL

4.Print “No Space Available (Overflow)! Exiting”

5.Else

6.{ newptr -> data = item

7.Newptr -> next = NULL

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 4

8. if start = NULL then9. start = newptr10. else {11. save = start12. start = newptr13. newptr -> next = save14. } }15. End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 5

IMPLEMENTATION OF THE ALGORITHM IN PROGRAM#include<iostream.h>

#include<conio.h>

#include<process.h>

struct node { int info;

node *next;

} *start,*newptr,*ptr,*save;

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 6

node* create_new_node( int n )

{ ptr=new node; ptr->info=n; ptr-

>next=NULL; return ptr; }

void insert_beg (node* np)

{ if(start==NULL) start=np; else { save=start; start=np; np->

next=save; } }

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 7

void display(node* np) { while (np!=NULL) { cout<<np-

>info<<" -> "; np=np->next ; } cout<<"\n!!!!!

>>>>>!!!!!!"; }

void main() { start= NULL;

int inf ; char ch='y';

while(ch=='y' || ch=='Y')

{clrscr();

cout<<"\n enter information of the new node..";

cin>>inf ; cout<<"\n

creating new node ! ! press enter to continue...";

getch();SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 8

newptr = creat_new_node(inf);

if( newptr!= NULL) {

cout<<"\n \n new code created successfully. press enter to cointinue.."; getch();

}

else

{ cout<<"\n cannot create new code \t "; exit(1);

}

cout<<"\n \t now inserting this node in the beginning of the list ";

cout<<"\n \t press enter continue ";

getch();

insert_beg(newptr);

cout<<"\n now the list is: \n";

display(start);

cout<<"\n \a \t press enter y to enter new node, n to exit: " ;

cin>>ch;

}

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 9

INSERTION OF THE NODE ( AT THE END)

Algorithm

1.Ptr = start

2.newptr = new node

3.If newptr = NULL

4.Print “No Space Available (Overflow)! Exiting”

5.Else

6.{ newptr -> data = item

7.newptr -> next = NULL

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 10

8. if start = NULL then {9. start = newptr10. rear = newptr

}8. else {9. rear -> next = newptr10. rear = newptr

} 8. End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 11

IMPLEMENTATION OF THE ALGORITHM IN PROGRAM

#include<iostream.h>

#include<conio.h>

#include<process.h>

struct node { int info;

node *next;

} *start,*newptr,*ptr,*save, *rear;

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 12

node* creat_new_node( int n )

{ ptr=new node; ptr->info=n; ptr-

>next=NULL; return ptr; }

void insert_End (node* np)

{ if(start==NULL){ start=np;

rear = np; } else { rear -> next = np;

rear = np; } }

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 13

void display(node* np)

{ while (np!=NULL) { cout<<np-

>info<<" -> "; np=np->next ; } cout<<"\n!!!!!

>>>>>!!!!!!"; }

void main() { start= rear =

NULL; int inf ; char ch='y';

while(ch=='y' || ch=='Y')

{clrscr();

cout<<"\n enter information of the new node..";

cin>>inf ; cout<<"\n

creating new node ! ! press enter to continue...";

getch();SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 14

newptr = creat_new_node(inf);

if( newptr!= NULL) {

cout<<"\n \n new code created successfully. press enter to continue.."; getch();

} else {

cout<<"\n cannot create new code \t "; exit(1);

}

cout<<"\n \t now inserting this node at the end of the list ";

cout<<"\n \t press enter continue "; getch(); insert_end(newptr); cout<<"\n now the list is: \n"; display(start); cout<<"\n \a \t press enter y to enter new node, n to exit: " ;

cin>>ch; } }

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 15

DELETION OF THE NODE FROM THE BEGINNING

Algorithm

1.If start = NULL then

2.Print “Underflow”

3.Else {

4.Ptr = start

5.Start = start ->next

6.Delete ptr }

7.End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 16

IMPLEMENTATION OF THE ALGORITHM IN PROGRAM

void DelNode( ){if (start == NULL)

cout << “\n Underflow!!!!!”;else

{ ptr = start; start = start ->next; delete ptr;}

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 17

STACK

A LIFO Structure

Can be implemented as an array or as a linked list.

Operations in Stack:Push (Addition of Elements)Pop (Removal / Deletion on elements)

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 18

STACK AS AN ARRAY (POP)

Algorithm

1.If top < -1 then

2.print “underflow !!!!!!! Aborting”

3.Else {

4.Data = stack [top]

5.Top = top -1 }

6.End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 19

STACK AS AN ARRAY (PUSH)

Algorithm

1.Top = - 1

2.Read item

3.If top == (size – 1) then4.Print “No Space Available (Overflow)!

Exiting”

5.Else

6.{ top = top + 1

7.Stack[top] = item }

8.End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 20

#include<iostream.h>#include<conio.h>#include<process.h>const int sz = 50;void push(int stack[], int &top, int ele) {

if(top == (sz - 1)){cout << "\n Stack overflow";exit(1);}

else{top ++;stack[top = ele;}

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 21

void pop(int stack[], int &top){if(top < 0){cout << "\n Underflow";exit(1);}else

cout << "\n Poped Element: " << stack[top--];

}void Display(int stack[], int top) { if(top == -1) return;for( int i = top; i >= 0; i--)

cout << stack[i] <<endl;}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 22

void main(){ int stack[sz], item, top = -1, res; char ch = 'y'; clrscr(); while(ch == 'y' || ch == 'Y') {

cout << "\n Enter item for insertion: ";cin >> item;push(stack, top, item);cout << "\n Do you want to enter more elements (y/n) : ";cin >> ch;}cout << "\n The stack now is: ";Display(stack, top);

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 23

cout << "\n Do you want to delete elements (y/n) : ";

cin >> ch;

while(ch == 'y' || ch == 'Y'){

pop(stack,top);

cout << "\n Do you want to enter more elements (y/n) : ";

cin >> ch;

}

cout << "\n The stack now is: ";

Display(stack, top);

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 24

STACK AS A LINKED LIST (PUSH)

Algorithm1.Newptr = new Node2.Newptr -> info = item; Newptr -> next =

NULL

3.If top == NULL) then4.top = Newptr5.Else6.{ Newptr -> next = top 7.top = Newptr }8.End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 25

STACK AS A LINKED LIST (POP)

Algorithm1.If top == NULL then2.Print “Stack is Empty

(Underflow)”, Exit3.Else {4.Print Top -> info5.Top = top -> next }6.End

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 26

IMPLEMENTATION OF THE ALGORITHM IN PROGRAM

#include<iostream.h>

#include<conio.h>

#include<process.h>

struct node { int info;

node *next;

} *top,*newptr,*ptr,*save;

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 27

node* creat_new_node( int n )

{ ptr=new node; ptr->info=n; ptr-

>next=NULL; return ptr; }

void Push (node* np)

{

if(top==NULL)

top = np;

else

{

save = top;

top = np;

np-> next = save;

}

}SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 28

void display(node* np)

{ while (np != NULL) { cout << np->info

<< " -> "; np = np->next ; } cout<<"\n!!!!!

>>>>>!!!!!!"; }

void Pop( ){

if (top == NULL){cout << “\n Underflow!!!!!”;exit(1);}

else{ ptr = top; top = top ->next; delete ptr;}

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 29

void main() { top = NULL;

int inf ; char ch='y';

while(ch=='y' || ch=='Y')

{clrscr();

cout<<"\n enter information of the new node..";

cin >> inf ; cout<<"\n

creating new node ! ! press enter to continue...";

getch();

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 30

newptr = creat_new_node(inf);

if( newptr != NULL) {

cout<<"\n \n new code created successfully. press enter to continue.."; getch();

} else {

cout<<"\n cannot create new code \t "; exit(1);

}

cout<<"\n \t now Pushing this node into the stack ";

cout<<"\n \t press enter continue ";

getch();

Push(newptr);

cout<<"\n now the Stack is: \n";

display(top);

cout<<"\n \a \t press y to enter new node, n to exit: " ;

cin>>ch;

}

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 31

APPLICATIONS OF STACK

Reversing a StringPolish StringConversion of Infix Expression to Postfix Expression

Evaluation of Postfix ExpressionProcessing of Function (Subprogram)

CallsMatching Parenthesis

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 32

Infix NotationOperators placed between two operands. E.g. A + B, A – B, A * B, A / B, A ^ B etc

Postfix Notation (Reverse Polish Notation)Operators placed after two operands. E.g. AB +, AB -, AB * etc.

Prefix Notation (Polish Notation)Operators placed before two operands. E.g. + AB, - AB, * AB etc.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 33

The Name Polish Notation and Reverse Polish Notation are named after Polish Logician Jan Lukasiewiez

CONVERSION FROM INFIX TO POST FIX (ALGORITHM)

1. Enclose the exp in Parenthesis i.e. ( )

2. Read Next symbol of the exp and repeat steps 3 to 6 until the stack is empty and go to step 7

3. If symbol read = operand then add it to Postfix Exp.

4. If symbol read = ‘(‘ then push it into the stack

5. If the symbol read = operator then 1. Repeat while (Priority of Top(stack) >= Priority of operator)

1. { pop operator from stack2. Add Operator to Postfix Expression }

2. Push Operator into Stack

6. if the Symbol read = ‘)’ then1. Repeat while (Top(stack) != ‘(‘ )

1. { pop operator from stack2. Add Operator to Postfix Expression }

2. Remove the ‘(‘, It must not be added to Postfix Expression

7. End SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 34

EVALUATION OF POSTFIX EXPRESSION:

1. START

2. Read the element

3. If element = operand then Push the element into stack

4. If element = operator then Pop two operands from stack (One operand in case of NOT

Operator) Evaluate the expression formed by two operands and the

operator. Push the result of expression into stack

5. If no more elements then Pop the result

6. Else Goto step 2

7. END

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 35

QUEUESARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 36

THE QUEUE OPERATIONS

A queue is like a line of people waiting for a bank teller. The queue has a front and a rear.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 37

$ $

FrontRear

THE QUEUE OPERATIONS New people must enter the

queue at the rear. The C++ queue class calls this a push, although it is usually called an enqueue operation.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 38

$ $

Front

Rear

THE QUEUE OPERATIONSWhen an item is taken from the queue, it always

comes from the front. The C++ queue calls this a pop, although it is usually called a dequeue operation.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 39

$ $

Front

Rear

ARRAY IMPLEMENTATION

A queue can be implemented with an array, as shown here. For example, this queue contains the integers 4 (at the front), 8 and 6 (at the rear).

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 40

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

An array of integers to An array of integers to implement a queue of implement a queue of integersintegers

4 8 6

We don't care what's inWe don't care what's inthis part of the array.this part of the array.

ARRAY IMPLEMENTATION

The easiest implementation also keeps track of the number of items in the queue and the index of the first element (at the front of the queue), the last element (at the rear).

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 41

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

4 8 6

sizesize3

firstfirst0

lastlast2

A DEQUEUE OPERATION

When an element leaves the queue, size is decremented, and first changes, too.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 42

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

4 8 6

sizesize2

firstfirst1

lastlast2

AN ENQUEUE OPERATION

When an element enters the queue, size is incremented, and last changes, too.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 43

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

28 6

sizesize3

firstfirst1

lastlast3

AT THE END OF THE ARRAY

There is special behavior at the end of the array. For example, suppose we want to add a new element to this queue, where the last index is [5]:

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 44

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ]

2 16

sizesize3

firstfirst3

lastlast5

AT THE END OF THE ARRAY

The new element goes at the front of the array (if that spot isn’t already used):

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 45

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ]

2 16

sizesize4

firstfirst3

lastlast0

4

ARRAY IMPLEMENTATION

Easy to implement

But it has a limited capacity with a fixed array

Or you must use a dynamic array for an unbounded capacity

Special behavior is needed when the rear reaches the end of the array.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 46

[ 0 ][ 0 ] [1][1] [ 2 ][ 2 ] [ 3 ][ 3 ] [ 4 ][ 4 ] [ 5 ][ 5 ] . . .. . .

4 8 6

sizesize3

firstfirst0

lastlast2

INSERTION IN THE QUEUE:Algorithm

1. Start2. If rear = null (-1) then {3. Rear = Front = 04. Queue [0] = item }5. Else if Rear = N – 1 then6. Print “OVERFLOW”7. Else 8. Queue [Rear ++ ] = item9. END

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 47

DELETION IN THE QUEUE:Algorithm

StartIf Front = null (-1) then Print “UNDERFLOW”Else {Item = Queue [Front] If Front = Rear Then

Front = Rear = 0 }

Else Front ++END

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 48

#include<iostream.h>

#include<conio.h>

#include<process.h>

int insert_in_Q(int[],int);

void display(int[],int,int);

const int size = 50;

int Q[size], front=-1, rear=-1;

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 49

Implementation of the Algorithm in Program :int insert_in_Q(int Q[ ], int

ele) {

if (rear==size-1)

return -1;

else if (rear==-1) {

front = rear = 0 ;

Q[rear]=ele; }

else {

rear++;

Q[rear]=ele; }

return 0;

}

int remove(int Q[ ]) {

int ret;

if(front == -1)

return -1 ;

else

{

ret = Q[front];

if(front==rear)

front=rear=-1;

else

front++;

}

return ret;

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 50

Implementation of the Algorithm in Program :void display (int Q[ ],int front ,int

rear)

{ if( front == -1) return; for(int i=front;

i<=rear; i++)

cout<<Q[i] << '\t';

}

void main() { clrscr(); int item, res ; char ch='y' ; while(ch=='y' || ch=='Y') { cout<<"\n\t enter element to

be inserted : ";cin>> item;res = insert_in_Q(Q,item);// res= remove(Q) if( res==-1) {cout<<"n!!! sorry OVERFLOW !!! aborting## "; exit(1); }

cout<<"\n \a\tnow the queue is : ";

display (Q,front,rear);cout<<"\n\t\twant to insert

more elements (y/n) :";cin>>ch; }

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 51

Implementation of the Algorithm in Program : cout << "\n DO you want to

remove items from the queue: ";

cin >> ch;

while(ch == 'y' || ch == 'Y') {

int de = remove(Q);

if (de == -1)

cout << "\n Queue is empty, !!!!! UNDERFLOW !!!!!!";

else {

cout << "\n Deleted item is : " << de;

cout<<"\n \a\tnow the queue is : ";

display (Q,front,rear);

cout << "\n Do you want to remove more items from the queue: ";

cin >> ch; } }}

LINKED LIST IMPLEMENTATION

A queue can also be implemented with a linked list with both a head and a tail pointer.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 52

10

15

7

null

13

head_ptr

tail_ptr

LINKED LIST IMPLEMENTATION

Which end do you think is the front of the queue? Why?

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 53

10

15

7

null

13

head_ptr

tail_ptr

LINKED LIST IMPLEMENTATION

The head_ptr points to the front of the list.

Because it is harder to remove items from the tail of the list.

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 54

10

15

7

nullhead_ptr

13

tail_ptr

Front

Rear

INSERTION IN THE QUEUE:Algorithm

1. Newptr = new Node

2. Newptr -> info = item; Newptr -> next = NULL

3. If Rear == NULL) then {

4. Front = Newptr

5. Rear = Newptr }

6. Else {

7. Rear -> next = Newptr

8. Rear = Newptr }

9. EndSARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 55

DELETION IN THE QUEUE:

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 56

Algorithm1. If Front = NULL then

2. Print “UNDERFLOW”

3. Else {

4. Ptr = Front

5. If Front = Rear Then

6. Front = Rear = NULL

7. Else Front = Front - > next }

8. Delete ptr

9. End

#include<iostream.h>#include<conio.h>#include<process.h>struct node { int info;

node *next; }

*front,*newptr,*ptr,*save,*rear ;

int itemdel;

node* creat_new_node( int n){ptr=new node; ptr->info=n; ptr->next=NULL;

return ptr; }

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 57

Implementation of the Algorithm in Program :void insert_end (node* np) {

if(front==NULL)

front= rear=np;

else {

rear->next= np;

rear=np; }

}

void display(node* np) {

while (np != NULL) {

cout << np->info << " -> ";

np = np->next ; }

cout<<"\n<--->";

}

void delnode_q( ){

if (front==NULL)cout << "\n < Underflow >";else{ ptr = front;

itemdel = ptr->info;

front = front ->next;

delete ptr;}

}

void main() { front = rear = NULL;

int inf ; char ch='y';SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 58

Implementation of the Algorithm in Program :while(ch=='y' || ch=='Y') {

clrscr();

cout<<"\n enter information of the new node..";

cin >> inf ;

cout<<"\n creating new node ! ! press enter to continue...";

getch();

newptr = creat_new_node(inf);

if( newptr == NULL) {

cout<<"\n \n CANNOT CREATE NODE";

exit(1);

getch(); }

insert_end(newptr );

cout<<"\n now the queue is :";

display(front);

cout<<"\n \a \t press y toenter new node, n to exit: " ;

cin>>ch;

}

cout<<"\n Do you want to delete element (y/n): " ;

cin >> ch;

while (ch == 'y' || ch == 'Y')

{

delnode_q();SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 59

Implementation of the Algorithm in Program :cout << "\n The deleted item

is: " << itemdel;

cout<<"\n now the Queue is: \n";

display(front);

cout<<"\n Do you want to delete another element (y/n): " ;

cin >> ch;

}

cout<<"\n now the Queue is: \n";

display(front);

getch();

}

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 60

SARAS M SRIVASTAVA, PGT (CS), KV, IISC, BANGALORE - 12 61

Questions

Recommended