0 Stimmen dafür0 Stimmen dagegen

4 Aufrufe41 Seitencontents:
Problem solving techniques and examples-Abstract Data Type (ADT)-The list ADT Arrays- Stacks and Queues: Implementation and Application, Circular Queues

Aug 19, 2017

© © All Rights Reserved

DOC, PDF, TXT oder online auf Scribd lesen

contents:
Problem solving techniques and examples-Abstract Data Type (ADT)-The list ADT Arrays- Stacks and Queues: Implementation and Application, Circular Queues

© All Rights Reserved

Als DOC, PDF, TXT **herunterladen** oder online auf Scribd lesen

4 Aufrufe

contents:
Problem solving techniques and examples-Abstract Data Type (ADT)-The list ADT Arrays- Stacks and Queues: Implementation and Application, Circular Queues

© All Rights Reserved

Als DOC, PDF, TXT **herunterladen** oder online auf Scribd lesen

- Isc Computer Project
- DA06
- Data Structures
- Stacks Queues Lists
- Stack C++
- Circular Linled List - Program
- chapter2.pdf
- DSA
- Stack & Queues basic
- Consolidated DSAD
- Questions WithAnswer Queue
- AdvCppLab_s1
- Practicals.docx
- 03-Lecture.pdf
- EEM 303 D.S. QB
- Data Structures
- dsc
- MCQs on Queue With Answers
- 08_DS and Algorithm_session_11.pps
- CSC PATTERN

Sie sind auf Seite 1von 41

Problem solving techniques and examples-Abstract Data Type (ADT)-The list ADT Arrays-

Stacks and Queues: Implementation and Application, Circular Queues

The act of finding a solution to a perplexing, distressing, vexing, or unsettled question

An algorithm is a clearly specified set of simple instructions to be followed to solve a

problem. Once an algorithm is given for a problem and decided (somehow) to be correct, an

important step is to determine how much in the way of resources, such as time or space, the

algorithm will require. An algorithm that solves a problem but requires a year is hardly of

any use.

Step 1. Identify and Select the Problem

The objective of this step is to identify the problem. That sounds simple enough, but

problems usually are tied to very emotional issues. Egos are usually connected to the

problem or the possible solution. Because the emotions are a part of the process, people can

miss reading the problem. So, the first step for everyone involved is to step back from the

issue and use the STAR method. The individual or group involved should take a look at

what is really causing the difficulty. This should be thoroughly thought through and agreed

upon so everyone is on the same page.

Consensus: This is a good time to bring up an agreement process that helps to bring

everyone to the same page of agreement, but that isnt easy. Consensus simply means

everyone is in agreement or they can live with the agreement. If they cannot live with the

agreement, the group or team has not reached consensus. Then, more discussion,

understanding each others point of view, and keeping an open mind are required. This

process requires cooperation, good intentions, and a willingness to be flexible about personal

feelings and issues. So consensus has these three elements:

1. I agree.

2. I dont fully agree, but I can live with and support the agreement.

3. I dont agree, and I cannot live with or support the agreement.

This process will become increasingly important as the group or team moves closer and

closer to selecting a solution to a problem. Using the process from the beginning brings the

whole group along at every step.

Now that the problem is defined, analyze it to see what is the real bottom-line. line root

cause. Often people get caught up in symptoms or effects of problem or issue and never get

down to the real cause. They get mad at someones attitude, anger, or actions, which are not

the cause of the problem. The key here is to focus everyones efforts on analyzing the

problem for the real cause. Once the cause is found, plans can be made to fix it

1

Step 3.Generate Potential Solutions

Now that the problem has been analyzed, the group can begin to develop possible solutions.

This is a creative as well as practical step where every possible solution or variation is

identified.

In this step use the brainstorming process that has been used in class before to generate as

many solutions as possible. There are no wrong answers here, and judgments should not be

passed on another persons suggestions.

Now that there are a wide variety of possible solutions, it is time to select the best solution to

fix the problem given the circumstances, resources, and other considerations. Here the group

is trying to figure out exactly what would work best given who they are, what they have to

work with, and any other considerations that will effect the solution.

This is the DO stage of PDSA. Make sure the solution can be tracked to have information to

use in the STUDY stage. This may seem to be an easy stage, but it really requires a scientific

approach to observing specifically what is going on with the solution.

This final step is the STUDY stage of PDSA. Did the solution work? If notwhy not? What

went right, and what went wrong? What adjustments does the group have to make to make

the solution work better?

This is a careful analysis stage that improves upon the best solution using the information

gathered during the DO stage.

After this analysis the group is ready to ACT upon their findings and the problem should be

solved or better under control.

Its a preliminary phase. In other words, we must analyze what must be done rather

than how to do it.

2. Getting Started on a problem

There are many ways of problem solving methods. it reviews the framework within

which computer science and the study of algorithms and data structures must fit, in

particular, the reasons why we need to study these topics and how understanding these

topics helps us to become better problem solvers.

3. The use of specific examples

In this technique, problem solver can pick specific example of a general problem we

wish to solve.

Eg: Finding Maximum of a set of numbers

4. Similarities among problem

By this technique we can bring as much past experience as possible to solve the problem.

Eg: Newtons relativity Law can be applied in varieties of problem.

5. Working backwards from the solution

2

In some cases, assume that we already know the solutions. This kind of problem may

solve by working backwards to the solutions.

Eg: Square root of 8

6. General Problem solving strategies

Different strategies appear to be good for different problems. Some of the well known

strategies are:

Divide and Conquer

Greedy Method

Dynamic Programming

Backtracking

Branch and Bound

For example,

Boolean = {false, true }

Digit = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }

Letter = { A, B, C,Z, a, b, c..z }

Data Structure: A Data Structure is a data object together with the relationships that exist

among the instances and among the individual elements that compose an instance. In other

words, we define Data Structure as a way of organizing data that considers not only the items

stored but also their relationship to each other.

Once a data structure has been chosen for a particular application, they have to be

handled in an efficient way. Hence there comes the necessity of studying Algorithms.

The two categories data structures are,

1. Linear Data Structures

2. Non-linear Data Structures

Linear data structures are those in which the elements form a sequence whereas non-linear data

structures are those in which the elements do not form a sequence.

Abstract Data Type (ADT): An Abstract Data Type is a representation in which we provide a

specification of the instances as well as of the operations that are to be performed. More

precisely,

An Abstract Data Type is a data type that is organized in such a way that the

specification of the object and the specification of the operation on the object are separated from

the representation of the object and the implementation of the operation.

operations from their specification, thus leading the way to object oriented programming.

3

Formula Based Representation:

In this method we use an array to represent the instances of an object. Each position of

array is called a cell or a node. Individual elements of an instance are located in the array using a

mathematical formula as shown.

Location (i) = i - 1 ith element is in position i-1 (if array starts with position zero)

(or)

Location (i) = i ith element is in position i (if array starts with position one)

A Linear list may be specified as an abstract data type (ADT) in which we provide a

specification of the instances as well as of the operations that are to be performed.

AbstractDataType LinearList

{

instances

ordered finite collection of zero or more elements

operations

Create( ): Create an empty linear list.

Destroy( ): Erase the list.

IsEmpty( ): Return true if the list is empty, false otherwise.

Length( ): Return the list size.

Find(k, x): Return kth element of the list in x and return false if not found.

Search(x): Return the position of x in the list otherwise return -1 if not found.

Delete(k): Delete the kth element.

Insert(k, x): Insert x just after kth element

Display( ): Display all elements of the list

}

There are two methods by which we can construct a linear data structure. They are,

Method 1: By using a sequence of memory locations. These are implemented using arrays.

Method 2: By using pointers or links. These are implemented using linked lists.

1. Lists

- The list can be implemented using arrays these are called linear lists or

ordered lists.

- The list can be implemented using pointers these are called linked lists.

2. Stacks

- The stacks can be implemented using arrays.

- The stacks can be implemented using linked.

3. Queues

- The queue can be implemented using arrays.

- The queue can be implemented using linked lists.

4

LIST ADT

Linear List: A Linear list is a data object whose instances are of the form ( e 1, e2, en), where n

is a finite natural number.

ei Element of the list.

n length of the list.

s size of the element.

The operations that are performed on a linear list are,

1. Create a list.

2. Delete a list.

3. Determine whether the list is empty.

4. Determine the length of the list.

5. Find the kth element.

6. Search for a given element.

7. Delete the kth element

8. Insert a new element.

9. Display all elements.

It can be implemented by two ways 1.Using Array 2. Using Linked List

LINKED LIST

Linked List: A Linked list is a collection of elements called nodes, each of which stores two

items called info and link. Info is an element of the list and a link is a pointer to the next element.

The linked list is also called a chain.

2. Doubly linked list

3. Circular linked list

Singly Linked List: A singly linked list is a linked list in which each node contains only one link

pointing to the next node in the list.

5

In a singly linked list, the first node always pointed by a pointer called HEAD. If the link of the

node points to NULL, then that indicates the end of the list.

1. Count the number of elements.

2. Add an element at the beginning of the list.

3. Add an element at the end of the list.

4. Insert an element at the specified position in the list.

5. Delete an element from the list.

6. Search x in the list.

7. Display all the elements of the list.

The Abstract Data Type of the linked list may be written as shown.

Addatbeg( x )

The operation Addatbeg( x ), adds the element k at the beginning of the existing list.

First a temporary pointer is created and made to point to the node where head is pointing. The

given element K is stored in a new node. Check if the list is empty. If so make link of new node

6

point to NULL and make Head to point to new, making it the first element of the list. If the list is

not empty, then the link of new is made to point to the first element of the existing list and Head

is made to point to the new node.

ADD AT BEGINING

lst()

Begin

head=NULL

ct=0

End

Function create()

Begin

temp=new node

Write"Enter the data:"

Read temp->data

End

Function insert_begin()

Begin

Call create()

temp->link=head

head=temp

ct=ct+1

End

Addatend( x )

The operation Addatend( x ), adds the given element x at the end of the existing list.

Initially it is checked whether the list is empty or not. If the list is empty then create a new node

7

New and add the value x to the info part of the node. The link part is made to point to NULL.

Then the Head is made to point this new node making it the first node. If the list already has

some nodes and now a new node is to be added to the end of the list, then create a temporary

pointer called Temp and make it to point to the Head initially. Then move the pointer the last

node and now create a new node with value x. Make the link part point to NULL. Now the link

of temp is made to point to the new node, thus making the new node as the last node of the list.

Function append()

Begin

if(head=NULL)

then

insert_begin()

else

create()

temp->link=NULL

prev=head

while(prev->link< >NULL)

Do

prev=prev->link

End while

prev->link=temp

ct=ct+1

End if

End

Insert In the middle at the given position

The operation Insert inserts the given element x in the k th position. A temporary pointer

Temp is created and made to point to Head. Now the Temp pointer is moved to the k 1 th node.

A new node with value x is created and the link of the new node is made to point to the position

8

where the link of temp is pointing. Then the link of temp is made to point to the new node. Thus

the given element is inserted in the position k.

Function insertin_mid()

Begin

Write "Enter the position:"

Read pos;

If head->link=NULL AND pos=1

then

Call insert_begin()

End if

If head->link==NULL AND pos=2

then

Call append()

End if

Else if pos>=2 AND pos<=ct

then

prev=head

for I = 2 to pos - 1 step +1

do

prev=prev->link

END FOR

next=prev->link

9

temp=new node

WriteEnter the data:"

Read temp->data

temp->link=next

prev->link=temp

ct=ct+1

else

Write "Enter a valid position & try again"

End if

End

Delete ()

The function Delete() deletes the node at the given position. The node previous which is the

previous node of the given postion is selected first. The next node connected to the previous is

the link of the positon to be deleted, thereby removing the node at the given position.

Function del()

Begin

if(head= NULL)

then

Write Empty list"

else

Write Enter the position:"

Read pos

if(pos==1)

then

next=head->link

head=next

ct=ct-1

else

if((pos>=2)&&(pos<=ct))

prev=head

for(int i=2;i<=pos-1;i++)

Do

prev=prev->link

End FOR

temp=prev->link

next=temp->link

prev->link=next

ct=ct-1

End if

End If

End

10

Search( x )

The operation Search( x ), searches the given value x in the list. If found returns the node

position where it is found. A temporary pointer Temp is created and made to point to the Head.

Now info part of Temp is compared with the value x. If the value matches the node position

number is returned otherwise Temp pointer is moved to the next node. This is repeated till the

end of the list is reached or till the element to be searched is found.

Function search()

Begin

flag=0

if(head=NULL)

then

Write Empty list"

else

Write Enter the element to be searched:"

Read e

cur=head

FOR I = 1 to ct Step +1

Do

if(cur->data= e)

then

pos=I

11

flag++

break

else

cur=cur->link

End if

ENDFOR

If (flag =1)

then

Write "Element found in position:" pos

else

Write Element not found"

End if

End Search

Display( )

The operation Display( ), displays all the value in each node of the list. A temporary

pointer is created and made to point to Head initially. Now info part of Temp is printed and

Temp is moved to the next node. This is repeated till the end of the list is reached.

Function display()

Begin

cur=head

cout<<"\nNo.of nodes is:"<<ct

cout<<"\nThe data is:"

while (cur< >NULL)

Do

Write "["<<cur->data<<"]->"

cur=cur->link

End while

End

Program

#include<iostream.h>

#include<conio.h>

#include<process.h>

class lst

{

private:

int ct,pos;

struct node

{

int data;

node *link;

}*temp,*next,*prev,*head,*cur;

public:

lst()

12

{

head=NULL;

ct=0;

}

void create()

{

temp=new node;

cout<<"Enter the data:";

cin>>temp->data;

}

void insert_begin()

{

create();

temp->link=head;

head=temp;

ct++;

}

void display()

{

cur=head;

cout<<"\nNo.of nodes is:"<<ct;

cout<<"\nThe data is:";

while(cur!=NULL)

{

cout<<"["<<cur->data<<"]->";

cur=cur->link;

}

cout<<"NULL";

}

void insertin_mid();

void append();

void del();

void search();

};

void lst::search()

{

int flag=0,e;

if(head==NULL)

{

cout<<"Empty list";

}

else

{

cout<<"Enter the element to be searched:";

cin>>e;

13

cur=head;

for(int i=1;i<=ct;i++)

{

if(cur->data==e)

{

pos=i;

flag++;

break;

}

else

{

cur=cur->link;

}

}

if(flag==1)

{

cout<<"Element found in position:"<<pos;

}

else

{

cout<<"Element not found";

}

}

}

void lst::del()

{

if(head==NULL)

{

cout<<"Empty list";

}

else

{

cout<<"Enter the position:";

cin>>pos;

if(pos==1)

{

next=head->link;

head=next;

ct=ct-1;

}

else

{

if((pos>=2)&&(pos<=ct))

{

prev=head;

14

for(int i=2;i<=pos-1;i++)

{

prev=prev->link;

}

temp=prev->link;

next=temp->link;

prev->link=next;

ct=ct-1;

}

}

}

}

void lst::append()

{

if(head==NULL)

{

insert_begin();

}

else

{

create();

temp->link=NULL;

prev=head;

while(prev->link!=NULL)

{

prev=prev->link;

}

prev->link=temp;

ct=ct+1;

}

}

void lst::insertin_mid()

{

cout<<"Enter the position:";

cin>>pos;

if((head->link==NULL)&&(pos=1))

{

insert_begin();

}

if((head->link==NULL)&&(pos=2))

{

append();

}

else if((pos>=2)&&(pos<=ct))

{

15

prev=head;

for(int i=2;i<=pos-1;i++)

{

prev=prev->link;

}

next=prev->link;

temp=new node;

cout<<"Enter the data:";

cin>>temp->data;

temp->link=next;

prev->link=temp;

ct=ct+1;

}

else

{

cout<<"Enter a valid position & try again";

}

}

void main()

{

int ch;

clrscr();

lst i;

do

{

cout<<"\nMenu:\n"<<"1.Insertion in beginning\n"<<"2.Insertion at append\n"<<"3.Insertion in

the middle\n"<<"4.Delete a node\n"<<"5.Searching a node\n"<<"6.Display\n"<<"7.quit\n";

cout<<"\nEnter the choice:";

cin>>ch;

switch(ch)

{

case 1:

i.insert_begin();

break;

case 2:

i.append();

break;

case 3:

i.insertin_mid();

break;

case 4:

i.del();

break;

case 5:

i.search();

16

break;

case 6:

i.display();

break;

default:

exit(0);

}

}while(ch<=6);

getch();

}

Menu: 1.Insert at beginning 2.Display 3.Insert middle 4.Append 5.Delete

Enter the choice 1

Enter the data 10

Menu: 1.Insert at beginning 2.Display 3.Insert middle 4.Append 5.Delete

Enter the choice 4

Enter the data 15

Menu: 1.Insert at beginning 2.Display 3.Insert middle 4.Append 5.Delete

Enter the choice 3

Enter the position 2

Enter the data 12

Menu: 1.Insert at beginning 2.Display 3.Insert middle 4.Append 5.Delete

Enter the choice 2

No of nodes = 3

10 -> 12-> 15 ->

Circular Linked List: Circular linked list is a linked list which consists of collection of nodes

each of which has two parts, namely the data part and the link part. The data part holds the

value of the element and the link part has the address of the next node. The last node of list has

the link pointing to the first node thus making the circular traversal possible in the list.

Logical representation of the circular linked list:

STACKS

The data structures seen so far, allows insertion and deletion of elements at any place.

But sometimes it is required to permit the addition and deletion of elements only at one end that

is either at the beginning or at the end.

17

Stacks: A stack is a data structure in which addition of new element or deletion of an existing

element always takes place at the same end. This end is often known as top of stack. When an

item is added to a stack, the operation is called push, and when an item is removed from the

stack the operation is called pop. Stack is also called as Last-In-First-Out (LIFO) list.

Operations on Stack:

There are two possible operations done on a stack. They are pop and push operation.

Pop: Allows removing an element from the top of the stack.

The Stack can be implemented using both arrays and linked lists. When dynamic

memory allocation is preferred we go for linked lists to implement the stacks.

Push operation:

If the elements are added continuously to the stack using the push operation then the

stack grows at one end. Initially when the stack is empty the top = -1. The top is a variable

which indicates the position of the topmost element in the stack.

PUSH(x)

If top = MAX 1

Then

Print Stack is full

Return

Else

Top = top + 1

A[top] = x

End if

End PUSH( )

18

Pop operation:

On deletion of elements the stack shrinks at the same end, as the elements at the top get

removed.

POP( )

If top = -1

Then

Print Stack is empty

Return

Else

Item = A[top]

A [Top] = 0

Top = top 1

Return item

End if

End POP( )

If arrays are used for implementing the stacks, it would be very easy to manage the

stacks. However, the problem with an array is that we are required to declare the size of the

array before using it in a program. This means the size of the stack should be fixed. We can

declare the array with a maximum size large enough to manage a stack.

As result, the stack can grow or shrink within the space reserved for it. The following program

implements the stack using array.

Program:

#include <iostream.h>

#include <conio.h>

class stack

{

private:

19

int a[MAX];

int top;

public:

stack();

void push(int x);

int pop();

void display();

};

stack::stack()

{

top=-1;

}

void stack::push(int x)

{

if (top==MAX-1)

{

cout<<"\nStack is full!";

return;

}

else

{

top++;

a[top]=x;

}

}

int stack::pop()

{

if (top==-1)

{

cout<<"\nStack is empty!";

return NULL;

}

else

{

int item=a[top];

top--;

return item;

}

}

void stack::display()

{

20

int temp=top;

while (temp!=-1)

cout<<"\n"<<a[temp--];

}

void main()

{

clrscr();

stack s;

int n;

s.push(10);

s.push(20);

s.push(30);

s.push(40);

s.display();

n=s.pop();

cout<<"\nPopped item:"<<n;

n=s.pop();

cout<<"\nPopped item:"<<n;

s.display();

getch();

}

Output:

40

30

20

10

Popped item:40

Popped item:30

20

10

Initially, when the stack is empty, top points to NULL. When an element is added using

the push operation, top is made to point to the latest element whichever is added.

Push operation:

Create a temporary node and store the value of x in the data part of the node. Now make

link part of temp point to Top and then top point to Temp. That will make the new node as the

topmost element in the stack.

21

PUSH(x)

Info(temp) = x

Link(temp) = top

Top = temp

End PUSH( )

Pop operation

The data in the topmost node of the stack is first stored in a variable called item. Then a

temporary pointer is created to point to top. The top is now safely moved to the next node below

it in the stack. Temp node is deleted and the item is returned.

POP ( )

If Top = NULL

Then

Print Stack is empty

Return

Else

22

Item = info (top)

Temp = top

Top = link (top)

Delete temp

Return item

End if

End POP( )

Program:

#include <iostream.h>

#include <conio.h>

class stack

{

private:

struct node

{

int data;

node *link;

};

node *top;

public:

stack();

~stack();

void push(int x);

int pop();

void display();

};

stack::stack()

{

top=NULL;

}

stack::~stack()

{

node *temp;

while (top!=NULL)

{

temp=top->link;

delete top;

top=temp;

}

}

void stack::push(int x)

23

{

node *temp;

temp=new node;

temp->data=x;

temp->link=top;

top=temp;

}

int stack::pop()

{

if (top==NULL)

{

cout<<"\nStack is empty!";

return NULL;

}

node *temp=top;

int item=temp->data;

top=temp->link;

delete temp;

return item;

}

void stack::display()

{

node *temp=top;

while (temp!=NULL)

{

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

temp=temp->link;

}

}

void main()

{

clrscr();

stack s;

int n;

s.push(10);

s.push(20);

s.push(30);

s.push(40);

s.display();

n=s.pop();

cout<<"\nPopped item:"<<n;

n=s.pop();

cout<<"\nPopped item:"<<n;

s.display();

getch();

}

24

Output:

40

30

20

10

Popped item:40

Popped item:30

20

10

APPLICATION OF STACKS

expression consists of operands and operators. The operands can be numeric values or numeric

variables. The operators used in an arithmetic expression represent the operations like addition,

subtraction, multiplication, division and exponentiation.

The arithmetic expression expressed in its normal form is said to be Infix notation, as

shown:

A+B

+ AB

AB +

Hence the given expression in infix form is first converted to postfix form and then evaluated to

get the results.

The function to convert an expression from infix to postfix consists following steps:

1. Every character of the expression string is scanned in a while loop until the end of the

expression is reached.

2. Following steps are performed depending on the type of character scanned.

(a) If the character scanned happens to be a space then that character is skipped.

(b) If the character scanned is a digit or an alphabet, it is added to the target string

pointed to by t.

25

(c) If the character scanned is a closing parenthesis then it is added to the stack by

calling push( ) function.

(d) If the character scanned happens to be an operator, then firstly, the topmost

element from the stack is retrieved. Through a while loop, the priorities of the

character scanned and the character popped opr are compared. Then following

steps are performed as per the precedence rule.

i. If opr has higher or same priority as the character scanned, then opr is

added to the target string.

ii. If opr has lower precedence than the character scanned, then the loop is

terminated. Opr is pushed back to the stack. Then, the character scanned

is also added to the stack.

(e) If the character scanned happens to be an opening parenthesis, then the operators

present in the stack are retrieved through a loop. The loop continues till it does

not encounter a closing parenthesis. The operators popped, are added to the target

string pointed to by t.

2. Now the string pointed by t is the required postfix expression.

Pseudocode:

CONVERSION(INFIX)

Begin

Read infix

L=Length(infix)

J=1

For i=1 to L

Do

C=infix(i)

If C is a number OR Alphabet Then

Postfix[j]= c

j=j+1

if C= ( Then

Push ( C )

if C= * || /|| + || || %

If top = 0 then

Push( C )

Else If Priority ( C ) < Priority (Stack[top] Then

Postfix[j]= pop()

J=j+1

Push( C )

Else

Push ( C )

if C= )

Then

Repeat

postfix[j]=pop()

j=j+1

Until (stk[top]< >'(')

26

pop()

End if

End For

Repeat

postfix[j]=pop()

j=j+1

Until (top > = 0)

(*Print the resultant postfix string*)

Write postfix

END CONVERSION(INFIX)

Begin

if (ch=='*'||ch=='/'||ch=='%') then

return 2

else if(ch=='+'||ch=='-') then

return 1

else return 0

END FUNCTION PRIORITY

FUNCTION PUSH(CHAR X)

Begin

Top=top+1

stk[top]=x

END FUNCTION PUSH

FUNCTION POP()

Begin

Top=top-1

return(stk[top])

END FUNCTION POP

Sample Output:

Stack is empty

The program takes the input expression in postfix form. This expression is scanned

character by character. If the character scanned is an operand, then first it is converted to a

digit form and then it is pushed onto the stack. If the character scanned is a blank space, then

it is skipped. If the character scanned is an operator, then the top two elements from the

27

stack are retrieved. An arithmetic operation is performed between the two operands. The

type of arithmetic operation depends on the operator scanned from the string s. The result is

then pushed back onto the stack. These steps are repeated as long as the string s is not

exhausted. Finally the value in the stack is the required result and is shown to the user.

EVALUATION ( POSTFIX )

Begin

Read postfix

L=Length(postfix)

For i=1 to L

Do

C=infix(i)

If C is a number OR Alphabet Then

(Get the value of C and store it in the stack)

Read n

Push(n)

Else if C= * || /|| + || || %

Then

Call eval(c)

End if

End for

(*Print the result *)

Result = pop()

Write Result

End EVALUATION ( POSTFIX )

FUNCTION EVAL(CHAR C)

Begin

x=pop()

y=pop()

SWITCH(C)

Begin

case '+': z=x+y

case '-': z=x-y

case '*': z=x*y

case '/': z=x/y

case '%': z=x%y

End SWITCH

push(z)

End EVAL

Sample Output:

Result is: 120

28

QUEUE

Queue: Queue is a linear data structure that permits insertion of new element at one end and

deletion of an element at the other end. The end at which the deletion of an element take place is

called front, and the end at which insertion of a new element can take place is called rear. The

deletion or insertion of elements can take place only at the front or rear end of the list

respectively.

The first element that gets added into the queue is the first one to get removed from the

list. Hence, queue is also referred to as First-In-First-Out list (FIFO). Queues can be represented

using both arrays as well as linked lists.

If queue is implemented using arrays, the size of the array should be fixed maximum

allowing the queue to expand or shrink.

Operations on a Queue

There are two common operations one in a queue. They are addition of an element to the

queue and deletion of an element from the queue. Two variables front and rear are used to point

to the ends of the queue. The front points to the front end of the queue where deletion takes

place and rear points to the rear end of the queue, where the addition of elements takes place.

Initially, when the queue is full, the front and rear is equal to -1.

Add(x)

An element can be added to the queue only at the rear end of the queue. Before adding

an element in the queue, it is checked whether queue is full. If the queue is full, then addition

cannot take place. Otherwise, the element is added to the end of the list at the rear side.

ADDQ(x)

If rear = MAX 1

Then

Print Queue is full

Return

Else

Rear = rear + 1

29

A[rear] = x

If front = -1

Then

Front = 0

End if

End if

End ADDQ( )

Del( )

The del( ) operation deletes the element from the front of the queue. Before deleting and

element, it is checked if the queue is empty. If not the element pointed by front is deleted from

the queue and front is now made to point to the next element in the queue.

DELQ( )

If front = -1

Then

Print Queue is Empty

Return

Else

Item = A[front]

A[front] = 0

If front = rear

Then

Front = rear = -1

Else

Front = front + 1

End if

Return item

End if

End DELQ( )

Program:

#include <iostream.h>

#include <conio.h>

30

const int MAX=10;

class queue

{

private:

int a[MAX], front, rear;

public:

queue();

void addq(int x);

int delq();

void display();

};

queue::queue()

{

front=rear=-1;

}

void queue::addq(int x)

{

if (rear==MAX-1)

{

cout<<"Queue is full!";

return;

}

rear++;

a[rear]=x;

if (front==-1)

front=0;

}

int queue::delq()

{

if (front==-1)

{

cout<<"Queue is empty!";

return NULL;

}

int item=a[front];

a[front]=0;

if (front==rear)

front=rear=-1;

else

front++;

return item;

}

31

void queue::display()

{

if (front==-1)

return;

for (int i=front; i<=rear; i++)

cout<<a[i]<<"\t";

}

void main()

{

clrscr();

queue q;

q.addq(50);

q.addq(40);

q.addq(90);

q.display();

cout<<endl;

int i=q.delq();

cout<<endl;

cout<<i<<" deleted!";

cout<<endl;

q.display();

i=q.delq();

cout<<endl;

cout<<i<<" deleted!";

cout<<endl;

i=q.delq();

cout<<i<<" deleted!";

cout<<endl;

i=q.delq();

getch();

}

Output:

50 40 90

50 deleted!

40 90

40 deleted!

90 deleted!

Queue is empty!

32

LINKED LIST IMPLEMENTATION OF QUEUE

Queue can be represented using a linked list. Linked lists do not have any restrictions on

the number of elements it can hold. Space for the elements in a linked list is allocated

dynamically; hence it can grow as long as there is enough memory available for dynamic

allocation. The queue represented using linked list would be represented as shown. The front

pointer points to the front of the queue and rear pointer points to the rear of the queue.

Addq(x)

In linked list representation of queue, the addition of new element to the queue takes

place at the rear end. It is the normal operation of adding a node at the end of a list.

ADDQ(x)

If front = NULL

Then

Rear = front = temp

Return

End if

Link(rear) = temp

Rear = link(rear)

End ADDQ( )

Delq( )

The delq( ) operation deletes the first element from the front end of the queue. Initially it

is checked, if the queue is empty. If it is not empty, then return the value in the node pointed by

front, and moves the front pointer to the next node.

DELQ( )

If front = NULL

Print Queue is empty

Return

Else

While front NULL

Temp = front

Front = link(front)

Delete temp

End while

End if

33

End DELQ( )

Program:

#include<iostream.h>

#include<conio.h>

#include<process.h>

class queue

{

private:

struct node

{

int data;

node*link;

}*head,*temp,*rear;

public:

queue()

{

head=NULL;

}

void create()

{

rear=new node;

cout<<"Enter the data:";

cin>>rear->data;

}

void insert();

void del();

void display();

};

void queue::insert()

{

create();

if(head==NULL)

{

rear->link=head;

head=rear;

}

else

{

temp=head;

while(temp->link!=NULL)

{

temp=temp->link;

}

rear->link=temp->link;

34

temp->link=rear;

}

}

void queue::del()

{

temp=head;

head=head->link;

}

void queue::display()

{

temp=head;

cout<<"\nThe data is:";

while(temp!=NULL)

{

cout<<"["<<temp->data<<"]->";

temp=temp->link;

}

cout<<"NULL";

}

void main()

{

int ch;

clrscr();

queue q;

do

{

cout<<"\nMenu:\n"<<"1.Insertion\n"<<"2.Deletion\n"<<"3.Display\n"<<"4.Quit\n";

cout<<"\nEnter the choice:";

cin>>ch;

switch(ch)

{

case 1:

q.insert();

break;

case 2:

q.del();

break;

case 3:

q.display();

break;

default:

exit(0);

}

}while(ch<=3);

getch();

}

35

CIRCULAR QUEUE (Application of the Queue)

In a Round Robin algorithm, the list is traversed in only one direction. The traversal can

be from one value to the next. But when the last value is reached, the control goes to the first

value and the process repeats. This Round Robin algorithm can be implemented using circular

queue as shown.

Algorithm:

//Initialization

quearr()

Begin

front=rear=ct=0;

Repeat FOR i=0 TO Max-1

que[i]=0;

End

Enqueue()

Begin

if(front==(rear+1)%MAX AND ct< >0)

then Write "que is full

else

Read x

rear=(front+ct)%MAX

que[rear]=x

ct=ct+1

End if

End Enque

deque()

Begin

if(front==rear AND ct==0)

then Write "queue empty"

36

else

que[front]=0;

ct=ct-1

front=(front+1)%MAX;

End if

End deque

disp()

Begin

if(ct>0)

then

for i = 0 to MAX -1

do

Write que[i]

Write No. Of elements : ct

END FOR

End disp

#include<iostream.h>

#include<process.h>

#include<conio.h>

#define MAX 2

class quearr

{

int x,front,rear,i,que[10],ct;

public:

quearr()

{

front=rear=ct=0;

for(int i=0;i<MAX;i++)

que[i]=0;

}

void enque();

void deque();

void disp();

};

void quearr::enque()

{

if(front==(rear+1)%MAX&&ct!=0) cout<<"que full"<<endl;

else

{

37

cin>>x;

rear=(front+ct)%MAX;

que[rear]=x;

ct++;

}

}

void quearr::deque()

{

if(front==rear&&ct==0) cout<<"queue empty"<<endl;

else

{

cout<<"Element dequeued is"<<que[front]<<endl;

que[front]=0;

ct--;

front=(front+1)%MAX;

}

}

void quearr::disp()

{

if(ct>0)

{

for(i=0;i<MAX;i++)

{

cout<<que[i]<<"\t";

}

cout<<"\nThere are "<<ct<<" elements in the queue";

}

}

void main()

{

quearr o;

clrscr();

int ch;

do

{

cout<<"\nMenu 1.enque 2.deque 3. display enter your choice: ";

cin>>ch;

switch(ch)

{

case 1: o.enque();

break;

case 2: o.deque();

break;

case 3: o.disp();

38

break;

default: exit(0);

}

}while(ch<=3);

getch();

}

Program:

#include<iostream.h>

#include<conio.h>

#include<process.h>

class queque

{

private:

struct node

{

int data;

node *link;

};

node *front, *rear;

int count;

int max;

public:

queque();

void enq();

void dq();

void display();

};

queque::queque()

{

front=rear=NULL;

count=0;

cout<<"Enter the maximum limit of the queque\n";

cin>>max;

}

void queque::enq()

{

if(count<max)

{

node *temp;

temp=new node;

cout<<"Enter the value : ";

cin>>temp->data;

39

if(front==NULL)

{

front=rear=temp;

rear->link=front;

}

else

{

temp->link=front;

rear->link=temp;

rear=temp;

}

count++;

}

else

{

cout<<"\nQueque overflow\n";

}

}

void queque::dq()

{ node *temp;

if(count==0)

{ cout<<"Queque is empty!\n"; }

else

{

cout<<"Element dequed is "<<front->data;

front=front->link;

count--;

}

}

void queque::display()

{ if(count>0)

{

node *temp;

temp=front;

int repeat =count;

do {

repeat--;

cout<<temp->data<<"\t";

temp=temp->link;

}while((temp!=front)&&(repeat>0));

}

}

void main()

{

40

int choice;

clrscr();

queque q;

do

{

cout<<"\nSelect your choice from the menu printed below\n";

cout<<"1. Enque\n";

cout<<"2. Deque\n";

cout<<"3. Display\n";

cout<<"4. Exit\n";

cin>>choice;

switch(choice)

{

case 1:

q.enq();

break;

case 2:

q.dq();

break;

case 3:

q.display();

break;

case 4:

exit(0);

}

}while(choice!=4);

getch();

}

*********************************

41

- Isc Computer ProjectHochgeladen vonArunav Ray
- DA06Hochgeladen vonasim_albakali
- Data StructuresHochgeladen vonViji Vinayaka
- Stacks Queues ListsHochgeladen vonAnkush Bhaal
- Stack C++Hochgeladen vonAida Raihanah
- Circular Linled List - ProgramHochgeladen vonGowtham
- chapter2.pdfHochgeladen vonPríñçe Súßåñth Prâßãñth
- DSAHochgeladen vonKumarecit
- Stack & Queues basicHochgeladen vonpinak
- Consolidated DSADHochgeladen vonPrakash Ayyappan
- Questions WithAnswer QueueHochgeladen vonkamoratwoothree
- AdvCppLab_s1Hochgeladen vonJnaneswar Reddy
- Practicals.docxHochgeladen vonAmandeep Kumar
- 03-Lecture.pdfHochgeladen voninbasaat talha
- EEM 303 D.S. QBHochgeladen vonshivam Gautam
- Data StructuresHochgeladen vontiwari_anunay1689
- dscHochgeladen vonprashanth10gm
- MCQs on Queue With AnswersHochgeladen vonBabuLalSaini
- 08_DS and Algorithm_session_11.ppsHochgeladen vonAjai Kumar
- CSC PATTERNHochgeladen vonKarthi Keyan
- Solution MTEHochgeladen vonManoj Kumar Choudhary
- FA18-MCS-055 data structure assignment 2.docxHochgeladen vonÂšjâd ÂLî Wâttôô
- Handout 1Hochgeladen vonVinod Partihar
- Java ScriptHochgeladen vonfmsarwar
- dsc-i-unit.pdfHochgeladen vonVamsi Versatile
- Programs for 3rd sem B.tech Data Structures LabHochgeladen vonRishabh
- Singly Linked List - Insert, Remove, Add, Count Source Code - CprogrammingHochgeladen vonSachin Puri
- Ds Lab ManualHochgeladen vonAyyanu Chelliah
- StacksHochgeladen vonKanwarpal Singh
- Linked hash presentationHochgeladen vonPhil

- 49_7-PDF_Mstower V6 User ManualHochgeladen vonArnanda Primadana
- SQL Server Replication.docxHochgeladen vonChiYinPhin
- 137673885assignments_for_class_xii_ip.pdfHochgeladen vonAshutosh Tripathi
- ESS FS DetailsHochgeladen vonkkumartamanam
- HackNEX Ethical Hacking Workshop ProposalHochgeladen vonRahul Batra
- LAKE Infor SunSystemsHochgeladen vonWasim.haider
- Information System GuidelinesHochgeladen vonShantel Mucheke
- PDW Optimization TechniqueHochgeladen vonavinashb3
- clash support AVEVA.pdfHochgeladen vonclaudiu hohota
- SerialHochgeladen vonNugroho Seget
- NHRA-FAQsHochgeladen vonAli Tanoli
- VisionMobile - The Evolving State of Mobile Commerce ReportHochgeladen vonVisionMobile
- SAP Spryng SMS Configuration GuideHochgeladen vonRAMAN
- CSENEW (1).docxHochgeladen vonyunush khan
- Descripcion BLE y TramasHochgeladen vonpurrutu
- Canon iR8070 Error Codes List.pdfHochgeladen vonGirish Kumar
- Solucionario Fisica Moderna Schaum DescargarHochgeladen vonHenry Payul
- ECG Com LaunchPadHochgeladen vonFrancisco Fambrini
- Marketing Strategies Adopted by HCL Info Systems Ltd. in Respect to Its Competitors NewHochgeladen vonrasi1719
- stm-1-63-e1-muxHochgeladen vonArthur Gouballe
- Data Management Complete Study GuideHochgeladen vonrajeshOtwani
- MirrorView Synchronous Command Line Interface (CLI) Reference 03Hochgeladen vonsreenathonweb
- hp-ux attach with vnxHochgeladen vonarungarg_it
- Implementing IBM Tivoli OMEGAMON XE for WebSphere Business Integration V1.1 Sg246768Hochgeladen vonbupbechanh
- 109T7219_E_Network Topology.pdfHochgeladen vonnabil160874
- Hirschmann IEEE 1588Hochgeladen vonJerry Holzer
- ext900sg.pdfHochgeladen vonscribdermaniac
- IntroductionToIntelx86-Part1Hochgeladen vonIgor R Souza
- Ansys Workbench ScriptingHochgeladen vonIhab El Sawi
- 8255 Programmable Peripheral InterfaceHochgeladen vonSivaprakasam Karthikeyan

## Viel mehr als nur Dokumente.

Entdecken, was Scribd alles zu bieten hat, inklusive Bücher und Hörbücher von großen Verlagen.

Jederzeit kündbar.