LUCKNOW PUBLIC SCHOOL
SESSION-2019-20
STUDY MATERIAL
FRAGMENT -2(PART-1)
SUBJECT: Computer Science(283)
CLASS-XII
CHAPTERS INCLUDED:
CHAPTER8: POINTERS
CHAPTER 2: LINKED LIST,STACK AND QUEUES
TEACHERS’ CONTRIBUTORS:
GAJENDRA SINGH DHAMI, PGT (CS), SOUTH-CITY
MOHIT TANDON,PGT(CS),SECTOR-D
Study Material - CS-XII Chap - 8 : Pointers 1
Study Material - CS-XII Chap - 8 : Pointers 1
CHAPTER – 8 : POINTERS
C++ Memory Map : Program Code : It holds the compiled code of the program. Global Variables : They remain in the memory as long as program continues. Stack : It is used for holding return addresses at function calls, arguments passed to the
functions, local variables for functions. It also stores the current state of the CPU. Heap : It is a region of free memory from which chunks of memory are allocated via DMA
functions. Free Store : It is a pool of unallocated heap memory given to a program that is used by the program for dynamic memory allocation during execution. What is a Pointer?
Pointer is a variable that holds a memory address of another variable of same type. It supports dynamic allocation routines. It can improve the efficiency of certain routines.
Declaration and Initialization of Pointers :
Syntax : <datatype> *pointer_name=&<variable name>;
Eg. int a=10; int *p=&a;
Eg. float x=12.5; float *ptr=&x;
Two special unary operator * and & are used with pointers. The & is a address operator that returns the memory address of its operand whereas the * is a pointer operator that returns the value of variable stored at specific address.
eg. int a = 10; int *p = &a; a p 65535 Here address of ‘a’ is stored in pointer ‘p’. cout<<p; will print 65535 cout<<*p; will print 10
Pointer to 1-d Numeric Array:- SYNTAX:- <datatype> *<pointer name> = <base address of array>;
Base address : the address of the very first element of the array is known as BASE ADDRESS.
BY: MOHIT TANDON PGT(CS) LPS SEC-D
10 10 65535
Study Material - CS-XII Chap - 8 : Pointers 2
Study Material - CS-XII Chap - 8 : Pointers 2
e.g. int a[5]={10,20,30,40,50}; int *p=&a[0];--------------------------------(1)
but C++ treats the name of an array as a pointer which contains base address i.e address of first element of array. Therefore we can also write- a=&a[0]---------------------------------------(2) combining (1) and (2) we get, int *p=a;--------------------------------------(3)
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
6500 6502 6504 6506 6508 p base address void main() { int a[5]={10,20,30,40,50}; int *p=a; cout<<p;will print base address (i.e 6500 as per diagram) cout<<*p;will print 10 Pointer arithmetic: Two arithmetic operations, addition and subtraction, may be performed on pointers. When you add 1 to a pointer, you are actually adding the size of whatever the pointer is pointing at. That is, each time a pointer is incremented by 1, it points to the memory location of the next element of its base type. Note: Two pointer variables cannot be multiplied or divided with each other.
Example:- int a[5]={10,20,30,40,50}; int *p=a;
a[0] a[1] a[2] a[3] a[4]
10 20 30 40 50
6500 6502 6504 6506 6508 p
cout<<p;will print 6500 cout<<*p;will print 10 p=p+4; cout<<p;will print 6508 cout<<*p;will print 50 p=p-2; cout<<p;will print 6504 cout<<*p;will print 30
Study Material - CS-XII Chap - 8 : Pointers 3
Study Material - CS-XII Chap - 8 : Pointers 3
p=a+3; cout<<p;will print 6506 cout<<*p;will print 40 Example-1: WAP to print the address and value of each array element using pointer. void main()
{ int marks[10] ={ 50,60,70,80,90,80,34,45,75,95}; int *m = marks; for(int i=0;i<10;i++) { cout<< “Address=”<<m<< “,”<< “Value=”<<*m; m++; //or ++m or m=m+1 or m+=1 }
}
Example-2: WAP to find the sum of even array elements. void main()
{ int a[5] ={ 50,60,70,80,90}; int *p = a; int sum=0; for(int i=0;i<5;i++) { if(*p%2==0) sum+=*p; p++; }
} OR
void main() {
int a[5] ={ 50,60,70,80,90}; int *p = a; int sum=0; for(int i=0;i<5;i++) { if(p[i]%2==0) sum+=p[i]; }
}
Pointer to String : Syntax:- char *<pointer-name>=<base address of string>;
Study Material - CS-XII Chap - 8 : Pointers 4
Study Material - CS-XII Chap - 8 : Pointers 4
E.g : char str*+ = “computer”;
char *cp; cp=str; //OR cp=&str[0]; cout<<str ; //display “computer” cout<<cp; // displays “computer” cout<<*cp; //displays ‘c’
Example-1: Program to print each character of a string on a new line using pointer. void main() { char str[50];
char *cp=str; gets(str);
for (int i=0; *cp != ‘\0’; i++) { cout <<*cp; // display character by character cp++; // incrementing the pointer to point to the next location }
} Example-2: Program to find the length of string using pointer. void main() { char str[50];
char *cp=str; int c=0;
gets(str); for (int i=0; *cp != ‘\0’; i++) // display character by character { c++; cp++; // incrementing the pointer to point to the next location }
} OR
void main() { char str[50];
char *cp=str; int c=0;
gets(str); for (int i=0; cp*i+ != ‘\0’; i++) // display character by character { c++; }
}
Example-3 : Give the output of the following program segment (assume all required header files are included in the program): void main() { char *NAME= “a ProFile”;
Study Material - CS-XII Chap - 8 : Pointers 5
Study Material - CS-XII Chap - 8 : Pointers 5
for(int x=0;x<strlen(NAME);x++) if(islower(NAME[x])) NAME[x]=toupper(NAME[x]); else if(isupper(NAME[x])) if(x%2!=0) NAME[x]=tolower(NAME[x-1]); else NAME[x]--; Cout<<NAME<<endl;
Output: A OROoILE
Passing the Pointer as an argument to a Function: When the pointers are passed to the function, the addresses of actual arguments in the calling function are copied into formal arguments of the called function. That means using the formal arguments (the addresses of original values) in the called function, we can make changing the actual arguments of the calling function. For example the program of swapping two variables with Pointers : #include<iostream.h> void main() {
void swap(int *m, int *n); int a = 5, b = 6; cout << “\n Value of a :” << a << “ and b :” << b; swap(&a, &b); cout << “\n After swapping value of a :” << a << “and b :” << b;
} void swap(int *m, int *n) {
int temp; temp = *m; *m = *n; *n = temp;
} Input : Value of a : 5 and b : 6 After swapping value of a : 6 and b : 5 Function returning Pointer : The way a function can returns an int, an float, it also returns a pointer. The general form of prototype of a function returning a pointer would be <datatype> * <function-name> (<argument list>);
Study Material - CS-XII Chap - 8 : Pointers 6
Study Material - CS-XII Chap - 8 : Pointers 6
#include <iostream.h> Int *min(int &, int &); void main() { int a, b, *c;
cout << “\nEnter a :”; cin >> a; cout << “\nEnter b :”; cint >> b; c = min(a, b); cout << “\n The minimum no is :” << *c;
} int *min(int &x, int &y) { if (x < y )
return (&x); else
return (&y) } Array of Pointers to Numbers: SYNTAX:- <datatype> *<pointer name>[size]; e.g. int *p[10]; Here , “p” is an array of 10 pointer that can store address of 10 integers. p[0] will store the address of 1st integer p[1] will store the address of 2nd integer And so on….. Example: int a=10,b=20,c=30; int *p[3]={&a,&b,&c}; for(int i=0;i<3;i++) { cout<<p[i]; //will print the address of a,b,c cout<<*p[i]; // will print the values of a,b,c }
Array of Pointers to Strings (String Pointer) : Syntax:-
char *<pointer-name>={“string1”, “string2”, “string3”,………….} An array of string pointer is very useful for storing multiple strings in memory. char *subject[] = { “Chemistry”, “Phycics”, “Maths”, “CS”, “English” }; In the above given declaration subject[] is an array of char pointers whose element pointers contain base addresses of respective names. That is, the element pointer subject[0] stores the base address of string “Chemistry”, the element pointer subject[1] stores the above address of string “Physics” and so forth.
Study Material - CS-XII Chap - 8 : Pointers 7
Study Material - CS-XII Chap - 8 : Pointers 7
An array of pointers makes more efficient use of available memory by consuming lesser number of bytes to store the string. An array of pointers makes the manipulation of the strings much easier. One can easily exchange the positions of strings in the array using pointers without actually touching their memory locations. Example:- void main() { char *subject*+ = , “Chemistry”, “Phycics”, “Maths”, “CS”, “English” -;
for(int i=0;i<5;i++) cout<<*subject[0]<< “-“<<subject*0+<< endl;
} Output: C-Chemistry P-Physics M-Maths C-CS E-English
Pointer to a Structure: C++ allows pointers to structures like other data types and these pointers to structures are known as structure pointers. Syntax: <structure name> *<pointer name>=&<structure variable>; The members of the structure are accessed by using -> (arrow operator). Example-1:- #include<iostream.h> struct Student { int rollno; char name[20]; }; void main() { Student s1=,901,”Pawan”-; Student *p=&s1; cout<<p->rollno; // will print 901 cout<<p->name; // will print Pawan } Example-2: Find the output of the following program: #include<iostream.h> struct Game {
char magic[20]; int score;
};
Study Material - CS-XII Chap - 8 : Pointers 8
Study Material - CS-XII Chap - 8 : Pointers 8
void main() {
Game M=,“Tiger”, 500-; char * Choice=&M; choice*4+=‟P‟; Choice*2+=‟L‟; M.Score+=5; cout<<Choice->magic<<Choice->score<<endl; Game N=M; N.Magic*0+=‟A‟; Magic*3+=‟J‟; N.Score-=120; cout<< N.Magic<<N.Score<<endl;
} Output: TiLeP550 AiLJP430 Pointer to a class (Object Pointer) : Syntax:- <classname> *<pointer name>=&<object name>; Example:- class Student { int rollno; char name[20]; public: Student(int rno,char nm[]) { rollno=rno; strcpy(name,nm); } void Show() { cout<<rollno<<”,”<<name<<endl; } }; void main() { Student s1(901,”Pawan”); Student *p=&s1; p->Show(); } “this” Pointer:
While defining a class the space is allocated for member functions only once and separate space is allocated for each object. There exists a serious problem i.e. which object‟s data member is to be manipulated by any member function.
Study Material - CS-XII Chap - 8 : Pointers 9
Study Material - CS-XII Chap - 8 : Pointers 9
The “this” pointer is an already created object pointer that points to currently calling object. The this pointer is automatically passed to a member function when it is called. For Example: #include<iostream.h> #include<string.h> #include<iostream.h> class Student { int rollno; char name[20]; public: Student(int rollno,char name[]) { this->rollno=rno; strcpy(this->name,nm); } void Show() { cout<<rollno<<”,”<<name<<endl; } }; Pointer to a Pointer:
We can store the address of a pointer pointing to a variable. Syntax: <datatype> **<pointer_to_pointer>=&<pointer name>; Example-1: void main() { int a=10; int *p=&a; int **q=&p; cout<<p; //will print address of a cout<<q; // will print address of p cout<<*p; //will print 10
cout<<**q; //will also print 10 } Static Memory Allocation : The amount of memory to be allocated is known in advance and it allocated during compilation, it is referred to as Static Memory Allocation. e.g. int a; // This will allocate 2 bytes for a during compilation.
Dynamic Memory Allocation(DMA) :
The amount of memory to be allocated is not known before hand rather it is required to be allocated as and when required during runtime, it is referred to as -
Dynamic Memory Allocation. C++ offers two operator for DMA – new and delete. e.g int x =new int; float y= new float; // dynamic allocation
delete x; delete y; //dynamic deallocation
Study Material - CS-XII Chap - 8 : Pointers 10
Study Material - CS-XII Chap - 8 : Pointers 10
Dynamic Allocation Operators : C++ dynamic allocation allocate memory from the free store/heap/pool, the pool of unallocated heap memory provided to the program. C++ defines two unary operators : (i) new - that performs the task of allocating memory during runtime and returns the
address of that memory location. (ii) delete - that performs the task of freeing memory allocated during runtime using “new”.
USES OF “new” OPERATOR:-
(i) to allocate memory for primitive data types: Syntax : <datatype> *<pointer-variable> = new <data-type>;
e.g. int * ptr= new int; Now ptr will point to memory allocated by “new” will initialize it with zero. cout<<ptr; //will print the address of the memory location cout<<*ptr; //will print 0 *ptr=5; cout<<*ptr;5 (ii) to allocate memory for 1-D Numeric Array:- Syntax : <datatype> *<pointer-variable> = new <data-type>[size];
e.g. int *ptr=new int[5]; Here ptr is pointer to an array of 5 integers whose elements will be initialized with zero. Example:-
int *ptr=new int[3]; for(int i=0;i<3;i++) { cout<<p[i]<<endl; } o/p:- 0 1 2
(iii) to allocate memory for 1-D Character Array:- Syntax : char *<pointer-variable> = new <data-type>[size];
e.g. char *ptr=new char[50]; Here ptr is pointer to a string initialized with null. Example:- void main() { char *ptr= new char[10];
cout<<ptr; // will print null ptr= “java”;
Study Material - CS-XII Chap - 8 : Pointers 11
Study Material - CS-XII Chap - 8 : Pointers 11
cout<<ptr; } o/p:- java Releasing Memory with “delete”:
Syntax for primitive types: For 1-D array :
delete pointer-variable; delete [size] pointer variable; eg. int *p=new int; ……… ……… delete p;
Eg. int *p=new int[5]; ……. ……. delete [ ] p;
(iv) to allocate memory for “structure”:-
Syntax:- <structure name>*<pointer name> = new <structure name>;
Example-1:- #include<iostream.h> struct Student { int rollno; char name[20]; }; void main() { Student *p=new Student; p->rollno=901; strcpy(p->name,”Pawan”); cout<<p->rollno; // will print 901 cout<<p->name; // will print Pawan }
(v) to allocate memory for an “object”:- Syntax:-
<class name>*<pointer name> = new <class name>; Example:- class Student { int rollno; char name[20]; public: void Enter(int rno,char nm[]) { rollno=rno; strcpy(name,nm); }
Study Material - CS-XII Chap - 8 : Pointers 12
Study Material - CS-XII Chap - 8 : Pointers 12
void Show() { cout<<rollno<<”,”<<name<<endl; } }; void main() { Student *p=new Student; p->Enter(101,”Rama”); p->Show(); }
Solved Questions
Q. 1 How is *p different from **p ? Ans : *p means, it is a pointer pointing to a memory location storing a value in it. But **p
means, it is a pointer pointing to another pointer which in turn points to a memory location storing a value in it.
Q. 2 How is &p different from *p ? Ans : &p gives us the address of variable p and *p. dereferences p and gives us the
value stored in memory location pointed to by p.
Q. 3 Find the error in following code segment : float **p1, p2;
p2 = &p1;
Ans : In code segment, p1 is pointer to pointer, it means it can store the address of another pointer variable, whereas p2 is a simple pointer that can store the address of a normal variable. So here the statement p2 = &p1 has error.
Q. 4 What will be the output of the following code segment ?
char C1 = ‘A’; char C2 = ‘D’; char *i, *j; i = &C1; j = &C2; *i = j; cout << C1;
Ans : It will print A.
Q. 5. Identify and explain the error(s) in the following code segment : float a[] = { 11.02, 12.13, 19.11, 17.41}; float *j, *k; j = a; k = a + 4; j = j * 2; k = k / 2; cout << “ *j = “ << *j << “, *k = “ << *k << “\n”;
Study Material - CS-XII Chap - 8 : Pointers 13
Study Material - CS-XII Chap - 8 : Pointers 13
Ans : The erroneous statements in the code are : j = j * 2; k = k / 2; Because multiplication and division operations cannot be performed on pointer and j and k are pointers.
Q.6. Give the output of the following program segment (assume all required header files are included in the program):
void main() {
char *s= “STUDY”; for(int x=0; x<strlen(s);x++) {for(int y=0; y<=x; y++) cout<<s[y]; cout<<endl;
}
}
Output: S ST STU STUD STUDY
Q.7. Find the output of the following program:
#include<iostream.h> void main() { int X[] = {10,25,30,55,110}; int *p = X; while(*p< 110) {
if (*p%3!=0)
*p =*p + 1; else *p =*p + 2; p++; } for(int i=4;i>=1;i--) , cout<<X*i+<<”@”; if (i%3==0) cout<<endl; } cout<<X[0]*3<<endl; }
Output: 110@56@ 32@26@33
Study Material - CS-XII Chap - 8 : Pointers 14
Study Material - CS-XII Chap - 8 : Pointers 14
HOME ASSIGNMENT
Problem 1: Give the output of the following program:
#include<iostream.h> void main( ) ,int a =32, *ptr = &a; char ch = „A‟, &cho =
ch; cho += a; *ptr += ch; cout << a << “ “<< ch << endl;
} Problem 2: Give the output of the following program (Assuming all required header files are
included in the program): void main( ) {
int array [ ]={ 2, 3, 4, 5}; int *arptr = array; int value =*arptr; value = *arptr++; cout << value <<‟\t‟; value = *arptr; cout << value <<‟\t‟; value = * ++arptr;
} Problem 3: Find the output of the following program:
#include <iostream.h> #include <string.h> class state { char *state_name; int size;
public: state() { size=0;
state_name = new char [size+1]; } state (char *s) { size = strlen(s);
state_name = new char[size + 1]; strcpy(state_name, s);
} void display( ) { cout<<state_name<<endl; } void Replace (state & a, state &b) { size = a.size + b.size;
delete state_name; state_name = new char[size + 1]; strcpy(state_name, a.state_name); strcat(state_name, b.state_name);
Study Material - CS-XII Chap - 8 : Pointers 15
Study Material - CS-XII Chap - 8 : Pointers 15
}}; void main( ) {
char * temp = “Delhi”; state state1(temp),state2(“Mumbai”),state3(“Nagpur”), S1, S2; S1.Replace(state1, state2); S2.Replae(S1, State3); S1.display(); S2.display();
} Problem 4: What will be the output of the following program:
#include<iostream.h> #include<ctype.h> #include<conio.h> #include<string.h> void changestring(char text[], int &counter) { char *ptr = text; int length=strlen(text); for(;counter<length-2;counter+=2,ptr++) { *(ptr+counter) = toupper(*(ptr+counter)); } } void main() { int position = 0; char message*+= “Mouse Fun”; changestring (Message, position); cout<<message<< “@” <<position; }
Problem 5: Find the output of the following program: #include<iostream.h> #include<string.h> class country { char *country name; int length;
public: country ( ) { length =0; country_name=new char [length+1]; } country (char *s) { length = strlen(s);
country_name=new char [length +1]; strcpy (country_name, s);
}
Study Material - CS-XII Chap - 8 : Pointers 16
Study Material - CS-XII Chap - 8 : Pointers 16
void display ( ) {cout<< country_name <<endl; } void Replace (country & a, country & b)
{ length a.length + b.length;
delete country_name; country_name=new char [length + 1]; strcpy (country_ name, a.country_name); strcat (country_name, b.country name);
} }; void main ( ) ,char * temp = “India”;
Country country1(temp),country2(“Bhutan”),country3(“Korea”),S1,S2; S1.Replace (country1, country2); S2.Replace (S1,country3); S1.display( ); S2.display ( );
} Problem 6: What will be the output of the following program?
#include<iostream.h> #include<ctype.h> #include<conio.h> #include<string.h> void changestring(char text[], int &counter) {char *ptr = text;
int length=strlen(text); for(;counter<length-2;counter+=2,ptr++) {*(ptr+counter) =
toupper(*(ptr+counter)); }
} void main() {clrscr();
int position = 0; char message*+= “Pointer Is Fun”; changestring (Message, position); cout<<message<< “@” <<position;
} Problem 7: What is ‘this’ pointer ? What is its significance ? Problem 8: What will be the output of following program ? #include<iostream.h>
void main() { char name1*+ = “ankur”; char name2*+ = “ankur”;
Study Material - CS-XII Chap - 8 : Pointers 17
Study Material - CS-XII Chap - 8 : Pointers 17
if (name1 != name2) cout << “\n both the strings are not equal”;
else cout << “\n the strings are equal”;
}
Problem 9: Give the output of the following code : void junk (int, int *);
int main() { int i = 6, j = -4; junk (i, &j); cout << “i = “ << i << “, j = “ << j << “\n”; return 0; } void junk(int a, int *b) { a = a* a; *b = *b * *b; }
Problem-9: Give the output of the following code : void DispScore(int S[],int N) { for(int Count = 0;Count<N;Count++) cout<<S[Count]<<"#"; cout<<endl; } void main() { int *Point,Score[]={10,5,20,15}; Point=Score; DispScore(Score,2); for(int Count=0; Count<4; Count++) { cout<<*Point<<":"; if(Count%2==0) Point++; else { *Point +=10; Point++; } } cout<<endl; DispScore(Score,4); } Problem-10: Write the output of the following C++ program code. void change(int *s) { for(int i=0;i<4;i++) { if(*s<40) { if(*s%2==0)
Study Material - CS-XII Chap - 8 : Pointers 18
Study Material - CS-XII Chap - 8 : Pointers 18
*s=*s+10; else *s=*s+11; } else { if(*s%2==0) *s=*s-10; else *s=*s-11; } cout<<*s<<" "; s++; } }
void main()
{ int score[]={25,60,35,53};
change(score); } Problem-11: Differentiate between the following two statements:
(i) int *ptr=new int; (ii) int *ptr=new int[5];
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Chapter 10:DATA STRUCTURES: STACKS, QUEUES AND LINKED LIST
A data structure is a particular way of storing and organizing data in a computer so that it can
be used efficiently. The data structure can be classified into following two types:
Simple Data Structure: These data structures are normally built from primitive data
types like integers,
floats, characters. For example arrays and structure.
Compound Data Structure: simple data structures can be combined in various ways to
form more complex structure called compound structures. Linked Lists, Stack, Queues
and Trees are examples of compound data structure.
Basic operation on data structures:
Insertion
Deletion
Traversal
Searching
Sorting
Merging
In this chapter our focus will be on insertion deletion and traversal operation.
Stack and Queue can be implemented in following ways:
Statically allocated(using an array of fixed size)
Dynamically allocated(using pointers)
STACK In computer science, a stack is a last in, first out (LIFO) data structure. A stack can is
characterized by only two fundamental operations: push and pop. The push operation adds an
item to the top of the stack. The pop operation removes an item from the top of the stack.
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack - letter
by letter - and then pop letters from the stack.
There are other uses also like:
1. Parsing(conversion)
2. Expression Conversion(Infix to Postfix, Postfix to Prefix etc)
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Steps showing operation on stack
An array to represent stack that can hold fixed number of elements,
top is an integer variable representing index of top element
Function push(stack,element,size) to insert element in stack
Function pop() to delete element from top
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Stack implementation using array(static allocation)
#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int stack[50]; //array to maintain stack
int size=50; //capacity of stack
int top=-1; //top represents top index of stack
void push(int n) // insert at top index
{
if(top==size-1)
cout<<"\nfull";
else
{
top++;
stack[top]=n;
}
}
void pop() //delete from top
{
if(top==-1)
cout<<"\nempty";
else
{
cout<<"\ndeleted="<<stack[top];
top--;
}
}
void traverse() //display status of stack
{
cout<<endl;
for(int i=top;i>=0;i--)
cout<<stack[i]<<"--";;
}
void main()
{clrscr();
top=-1;
int n;
for(int i=1;i<=5;i++)
{
cout<<"\nenter data=";
cin>>n;
push(n);
traverse();
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
cout<<”\ntop element deleted”<<endl;
pop();
traverse();
}
//Class implementation of stack
#include<iostream.h>
const int size = 50
class stack
{
int a[size]; //array a can store maximum 5 item of type int of the stack
int top; //top will point to the last item pushed onto the stack
public:
stack( ) //constructor to create an empty stack, top=-1 indicate that
no item is
{top = -1 ;} //present in the array
void push(int item)
{
if(top==size-1)
cout<<”stack is full, given item cannot be added”;
else
a[++top]=item; //increment top by 1 then item at new position
of the top in //the array a
}
int pop()
{
if (top==-1)
{
out<<”Stack is empty “;
return -1; //-1 indicates empty stack
}
else
return a[top--];//return the item present at the top of the stack then
decrement top by 1
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
}
void traverse()
{
cout<<endl;
for(int i=top;i>=0;i--)
cout<<a[i]<<"--";;
}
};
void main()
{
stack s1;
s1.push(3);
s1.push(5);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop();
}
QUEUE
Queue is a linear data structure which follows First in First out (FIFO) rule in which a
new item is inserted at the rear end and deletion of item is from the front end of the queue. In
a FIFO data structure, the first element added to the queue will be the first one to be removed.
Applications of Queue:
Queue, as the name suggests is used whenever we need to manage any group of objects in an
order in which the first one coming in, also gets out first while the others wait for their turn,
like in the following scenarios:
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling them
in an order, until a service representative is free.
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order
as they arrive i.e First come first served.
Steps showing queue operation
An array to hold elements in a queue having static size
Insertion at rear(tail) [rear is a integer variable holding index of last element in a queue]
Deletion from front(head) [front is a integer variable holding index of first element in a
queue]
Linear Queue implementation using Array
#include<stdio.h>
#include<iostream.h>
int q[5]; // aray to maintain queue
int first=-1; //index of first element
int last=-1; //index of last element
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
const int size=5;
void insert(int e) //insert at last
{
if(last==size-1)
{
cout<<"\nfull";
}
else if(last==-1)
{
first=last=0;
q[last]=e;
}
else
{
q[++last]=e;
}
}
void del()// delete element from front
{
if(first==-1)
{
cout<<"\nempty";
}
else if(first==size-1)
first=last=-1;
else
{
cout<<"\ndeleted element="<<q[first];
first++;
}
}
void traverse()// display status of queue
{cout<<"\nstatus\n";
for(int i=first;i<=last;i++)
cout<<"\t"<<q[i];
}
void main()
{int i,n;
for(i=0;i<5;i++)
{
cout<<"\nenter element to be inserted=";
cin>>n;
insert(n);
}
traverse();
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
cout<<"\ndelete element;";
del();
del();
traverse();
}
//class implementation of static queue
#include<iostream.h>
const int size=5; // size of queue
class queue
{ int front , rear;
int a[size];
public:
queue() //Constructor to create an empty queue
{ front=-1;
rear=-1;
}
void addQ(int item ) // insertion in array queue
{ if(rear==size-1)
cout<<”queue is full<<endl;
else if(front=-1)
front=rear=0;
a[rear]=item;
else
a[++rear]=item;
}
int delQ( ) // deletion from the array queue
{ if(front==rear)
{
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
cout<<”queue is empty”<<endl;
return 0;
}
else
return a[front++];
}
void traverse()//display contents
{
for(int i=front;i<=rear;i++)
cout<<a[i]<<”<-“;
}
};
void main()
{
queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
CIRCULAR QUEUE using array:
#include<iostream.h>
const int size=5; // size of queue
class Cqueue
{ int front , rear;
int a[size];
public:
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Cqueue() //Constructor to create an empty queue
{ front=-1;
rear=-1;
}
void addQ(int item ) // insertion in array queue
{ if(rear==size-1&&front==0||front==rear+1)
cout<<”queue is full<<endl;
else if(front=-1)
{front=rear=0;
a[rear]=item;}
else if(rear==size-1)
{rear=0;
a[rear]=item;}
else if(rear==size-1)
a[++rear]=item;
}
int delQ( ) // deletion from the array queue
{ if(front==-1)
{
cout<<”queue is empty”<<endl;
return 0;
}
else if(front==rear)
{int p= a[front++];
front=rear=-1;
return p;
}
else if(front==size-1)
{
int p= a[front];
front=0;
return p;
}
else
return a[front++];
}
void traverse()//display contents
{
if(front<=rear)
for(int i=front;i<=rear;i++)
cout<<a[i]<<”<-“;
else
{
for(int i=front;i<=size-1;i++)
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
cout<<a[i]<<”<-“;
for(int i=0;i<=rear;i++)
cout<<a[i]<<”<-“;
}
}
};
void main()
{
queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
LINKED LIST: In Computer Science, a linked list (or more clearly, "singly-linked list") is a data
structure that consists of a sequence of nodes each of which contains data and a pointer which
points (i.e., a link) to the next node in the sequence.
Advantages of Linked Lists
They are a dynamic in nature which allocates the memory when required.
Insertion and deletion operations can be easily implemented.
Stacks and queues can be easily executed.
Linked List reduces the access time.
What is a Node?
A Node in a linked list holds the data value and the pointer which points to the location
of the next node in the linked list.
Number of Nodes are connected, to form a Linked list.
A Node is formed using a self-referential structure.
struct Node
{
int data; //information
Node *next; // can holds address of next Node
};
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
In the picture above we have a linked list, containing 4 nodes, each node has some data(A, B,
C and D) and a pointer which stores the location of the next node.
Head Node(start) holds address of first element
Last Node holds address of Last Element and it point to NULL(end of list)
Insertion at front:
Last
Last
New Head
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Insertion at last:
Deletion from front:
#include<stdio.h>
#include<iostream.h>
struct node // self referential structure
{
int data;
node *next;
};
node *start,*nnode,*last;
void insert(int p) // insert at a given position
{
node *t=start,*m;
nnode =new node;
cout<<"\nenter data=";
cin>>nnode->data;
nnode->next=NULL;
int i=1;
while(i<p-1)
{
t=t->next;
i++;
}
nnode->next=t->next;//->next;
Last
Last
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
t->next=nnode;
}
void insert_last()//insert at last
{
nnode=new node;
cout<<"\nenter data=";
cin>>nnode->data;
nnode->next=NULL;
if(start==NULL)
{
start=last=nnode;
}
else
{last->next=nnode;
last=nnode;
}
}
void disp()// display status of list
{
node *p=start;
while(p!=NULL)
{
cout<<p->data<<"--";
p=p->next;
}
}
void inserts()//insert before start node
{
nnode=new node;
cout<<"\nenter data=";
cin>>nnode->data;
nnode->next=NULL;
nnode->next=start;
start=nnode;
}
void del_s()// delete front node
{
if(start==NULL)
cout<<"\nempty";
else
{
node *p=start;
start=start->next;
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
p=NULL;
delete p;
}
}
void main()
{
start=last=NULL;
cout<<”\ninsert at last”<<endl;
for(int i=1;i<=4;i++)
{
insert_last();
disp();
}
Cout<<”\ninsert at beginning”<<endl;
for(int j=1;j<4;j++)
{inserts();
disp();
}
cout<<"\ndelete from front="<<endl;
del_s();
disp();
cout<<"\ninsert in between\n";
insert(3);
disp();
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Stack implementation using linked list
#include<iostream.h>
struct node
{
int item; //data that will be stored in each node
node * next; //pointer which contains address of another node
}; //node is a self-referential structure which contains reference of another object type node
class stack
{
node *top;
public:
stack() //constructor to create an empty stack by initializing top with
NULL
{ top=NULL; }
void push(int item);
int pop();
~stack();
};
void stack::push(int item) //to insert a new node at the top of the stack
{
node *t=new node; //dynamic memory allocation for a new object of node type
if(t==NULL)
cout<<”Memory not available, stack is full”;
else
{
t->item = item;
t->next = top; //newly created node will point to the last inserted
//node or NULL if stack is empty
top=t; //top will point to the newly created node
}
}
int stack::pop() //to delete the last inserted node,which is currently pointed by the top
{
if(top==NULL)
{
cout<<”Stack is empty \n”;
return 0; // 0 indicating that stack is empty
}
else
{
node *t=top; //save the address of top in t
int r=top->item; //store item of the node currently pointed by top
top=top->next; // move top from last node to the second last node
delete t; //remove last node of the stack from memory
return r;
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
}
stack::~stack() //de-allocated all undeleted nodes of the stack when stack goes out of scope
{
node *t;
while(top!=NULL)
{
t=top;
top=top->next;
delete t;
}
void traverse()
{
node *p=start;
while(p!=NULL)
{
cout<<p->item<<"--";
p=p->next;
}
};
void main()
{
stack s1;
s1.push(3);
s1.push(5);
s1.push(7);
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
cout<<s1.pop()<<endl;
}
Queue implementation using Linked list
#include<iostream.h>
struct node
{ int item;
node *next;
};
class queue
{
node *front, *rear;
public:
queue( ) // constructor to create empty queue
{ front=NULL;
rear=NULL;
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
}
void addQ(int item);
int delQ();
void traverse(){
node *temp=front;
while(temp!=NULL)
{
cout<<temp->item<<”->”;
temp=temp-next;
}
};
void queue::addQ(int item)
{
node * t=new node;
t->item=item;
t->next=NULL;
if (rear==NULL) //if the queue is empty
{ rear=t;
front=t; //rear and front both will point to the first node
}
else
{ rear->next=t;
rear=t;
}
}
int queue::delQ()
{
if(front==NULL)
cout<<”queue is empty”<<return 0;
else
{ node *t=front;
int r=t->item;
front=front->next; //move front to the next node of the queue
if(front==NULL)
rear==NULL;
delete t;
return r;
}
void traverse()
{
node *p=start;
while(p!=NULL)
{
cout<<p->item<<"--";
p=p->next;
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
}
void main()
{
queue q1;
q1.addQ(3);
q1.addQ(5) ;
q1.addQ(7) ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl ;
cout<<q1.delQ()<<endl;
cout<<q1.delQ()<<endl;
}
Application of stacks in infix expression to postfix expression conversion:
Infix expression operand1 operator operand2 for example a+b
Postfix expression operand1 operand2 operator for example ab+
Prefix expression operator operand1 operand2 for example +ab
Some example of infix expression and their corresponding postfix expression
Infix expression Postfix expression
a*(b-c)/e abc-*e/
(a+b)*(c-d)/e ab+cd-*e/
(a+b*c)/(d-e)+f abc*+de-/f+
Algorithm to convert infix expression to postfix expression using stack:- Suppose x is an infix expression and find postfix expression Y
1. Push “(“ to the STACK, and add “)” to the end of X.
2. Scan X from left to right and REPEAT Steps 3 to 6 for each element of X UNTIL the
STACK is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it on to STACK.
5. If an operator is encountered then:
(a) Repeatedly pop from STACK and add to Y each operator which has the same
precedence as or higher precedence than operator.
(b) Add operator to STACK.
6. If a right parenthesis is encountered. Then:
(a) Repeatedly pop from the STACK and add to Y each operator until a left parenthesis
is encountered.
(b) Remove the left parenthesis.
7. End
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
For example convert the infix expression (A+B)*(C-D)/E into postfix expression showing
stack status after every step.
Symbol scanned from infix Stack status Postfix expression
(
( ((
A (( A
+ ((+ A
B ((+ AB
) ( AB+
* (* AB+
( (*( AB+
C (*( AB+C
- (*(- AB+C
D (*(- AB+CD
) (* AB+CD-
/ (/ AB+CD-*
E (/ AB+CD-*E
) AB+CD-*E/
Answer: Postfix
expression of
(A+B)*(C-D)/E is
AB+CD-*E/
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Evaluation of Postfix expression using Stack:
Algorithm to evaluate a postfix expression .
/*Reading of expression takes place from left to right*/
1. Read the next element //First element for the first time
2. If element is an operator then push the element in the Stack
3. If the element is an operator then
{
4. Pop two operands from the stack //pop one operator in case of unary
operator
5. Evaluate the expression formed by the two operands and the operator
6. Push the result of the expression in the stack.
}
7. If no-more-elements then
Pop the result
Else
Go to step 1.
8. End.
Example1: Evaluate the following postfix expression showing stack status after every step
8, 2, +, 5, 3, -, *, 4 /
token scanned from
postfix expression
Stack status after
processing the scanned
token
Operation performed
8 8 Push 8
2 8, 2 Push 2
+ 10 Op2=pop() i.e 2
Op1=pop() i.e 8
Push(op1+op2) i.e. 8+2
5 10, 5 Push(5)
3 10, 5, 3 Push(3)
- 10, 2 Op2=pop() i.e. 3
Op1=pop() i.e. 5
Push(op1-op2) i.e. 5-3
* 20 Op2=pop() i.e. 2
Op1=pop() i.e. 10
Push(op1-op2) i.e. 10*2
4 20, 4 Push 4
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
/ 5 Op2=pop() i.e. 4
Op1=pop() i.e. 20
Push(op1/op2) i.e. 20/4
NULL Final result 5 Pop 5 and return 5
Example2:Evaluate the following Boolean postfix expression showing stack status after every
step
True, False, True, AND, OR, False, NOT, AND
token scanned from
postfix expression
Stack status after
processing the scanned
token
Operation performed
True True Push True
False True, False Push False
True True, False, True Push True
AND True, False Op2=pop() i.e. True
Op1=pop() i.e. False
Push(Op2 AND Op1) i.e. False
ANDTrue=False
OR True Op2=pop() i.e. False
Op1=pop() i.e. True
Push(Op2 OR Op1) i.e. True OR
False=True
False True, False Push False
NOT True, True Op1=pop() i.e. False
Push(NOT False) i.e. NOT
False=True
AND True Op2=pop() i.e. True
Op1=pop() i.e. True
Push(Op2 AND Op1) i.e. True
AND True=True
NULL Final result True Pop True and Return True
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
SOLVED EXERCISES:
Q1. Write a function in C++ to perform a PUSH operation in a dynamically allocated stack
considering the following:
struct node
{ int x,y;
node *Link;
};
Ans : struct node
{ int x,y;
node *Link;
}*top, *temp;
void PUSH(node *np)
{
if(top = = NULL)
top = np;
else
{
temp = top;
top = np; // New node becomes to the first node
npLink = temp;
}
}
Q2. Write a function in C++ to perform Insert operation in a dynamically allocated Queue
containing names of students.
struct stud
{
char Name[20];
stud *Link;
};
Ans : struct stud
{
char Name[20];
stud *Link;
} *front, *rear;
void Insert(stud *np)
{
if (front = = NULL)
front = rear = np;
else
{
rearLink = np;
rear = np;
}
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
Q3. Write a function in C++ to perform Push operation on a dynamically allocated Stack
containing real numbers. struct NODE{
float Data; NODE *Link;
};
Ans: class STACK
{
NODE *Top;
public:
STACK();
void Push();
void Pop();
};
void STACK::Push()
{
NODE *Temp;
Temp=new NODE;
cin>>TempData;
TempLink=Top;
Top=Temp;
}
Q.4. Define functionstackpush( ) to insert nodes and stack pops ( ) to delete nodes . for a linked
list implemented stack having the following structure for each node
struct Node
{
Char name [ 20 ]
Int age ;
Node * link ;
};
Class stuck {
Node * top ;
Public
Stack ( ) { top = null ;} ;
Void stackpush ( );
Void stack pop ( ) ;
}
Ans
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
// Declares a stack structure
struct node
{
char name[20];
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
int age;
node *link;
};
class stack
{
node *top;
public :
stack() { top = NULL; }
void stackpush(); // Add stack
void stackpop(); // Delete stack
void show_Stack(); // Show stack
};
// Function body for adds stack elements
void stack::stackpush()
{
int val;
node *temp;
temp = new node;
cout << "Enter name : ";
gets(temp->name);
cout << "Enter age : ";
cin >> temp->age;
temp->link = NULL;
if(top ==NULL)
top = temp;
else
{
temp->link = top;
top = temp;
}
}
// Function body for delete stack elements
void stack::stackpop()
{
node *temp;
if (top == NULL)
{
cout << "Stack Empty ";
}
else
{
temp = top;
top = top->link;
temp->link = NULL;
delete temp;
}
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
}
// Function body for show stack elements
void stack :: show_Stack()
{
node *temp;
temp = top;
clrscr();
cout << "The values are \n";
while (temp != NULL)
{
cout << "\n" << temp->name << "\t" << temp->age;
temp = temp->link;
}
}
// Main programming logic
void main()
{
int choice;
stack STACK;
char opt = 'Y'; // To continue the do loop in case
clrscr();
do
{
cout << "\n\t\t Main Menu";
cout << "\n\t1. Addition of Stack";
cout << "\n\t2. Deletion from Stack";
cout << "\n\t3. Traverse of Stack";
cout << "\n\t4. Exit from Menu";
cout << "\n\nEnter your choice from above ";
cin >> choice;
switch (choice)
{
case 1:
do
{
STACK.stackpush();
cout<<"Do you want to add more elements<Y/N>?";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 2:
opt = 'Y'; // Initialize for the second loop
do
{
STACK.stackpop();
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
cout<<"Do you want to delete more element<Y/N>?";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 3:
STACK.show_Stack();
break;
case 4:
exit(0);
}
}
while (choice != 4);
}
Q. 5. Declare a stack using array that contains int type numbers and define pop and push
function using C++ Syntax.
Ans
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100 // Shows maximum array length
int stack[MAX]; // Declares array global variable
int top; // Declares integer top
// Function prototypes of add stack, delete stack, and
// show stack in array implementation
void push(int stack[], int val, int &top); // Add stack
int pop(int stack[], int &top); // Delete stack
void show_Stack(int stack[], int top); // Show stack
void main()
{
int choice, val;
char opt = 'Y'; // To continue the do loop in case
top = -1; // Initialization of Queue
clrscr();
do
{
cout << "\n\t\t Main Menu";
cout << "\n\t1. Addition of Stack";
cout << "\n\t2. Deletion from Stack";
cout << "\n\t3. Traverse of Stack";
cout << "\n\t4. Exit from Menu";
cout << "\n\nEnter your choice from above -> ";
cin >> choice;
switch (choice)
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
{
case 1:
do
{ cout << "Enter the value to be added in the stack ";
cin >> val;
push(stack, val, top);
cout <<"\nDo you want to add more elements <Y/N> ? ";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 2:
opt = 'Y'; // Initialize for the second loop
do
{ val = pop(stack, top);
if (val != -1)
cout << "Value deleted from statck is " << val;
cout <<"\nDo you want to delete more elements<Y/N>?";
cin >> opt;
} while (toupper(opt) == 'Y');
break;
case 3:
show_Stack(stack, top);
break;
case 4:
exit(0);
}
}
while (choice != 4);
}
// Function body for add stack with array
void push(int stack[], int val, int &top)
{
if (top == MAX - 1)
{ cout << "Stack Full ";
}
else
{ top = top + 1;
stack[top] = val;
}
}
// Function body for delete stack with array
int pop(int stack[], int &top)
{
int value;
if (top < 0)
{ cout << "Stack Empty ";
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
value = -1;
}
else
{ value = stack[top];
top = top - 1;
}
return (value);
}
// Function body for show stack with array
void show_Stack(int stack[], int top)
{
int i;
if (top < 0)
{ cout << "Stack Empty";
return;
}
i = top;
clrscr();
cout << "The values are ";
do
{ cout << "\n" << stack[i];
i = i - 1;
}while(i >= 0);
}
Q6.Differentiate between
(i) Linear Queue and Circular Queue
(ii) A Queue and a Dequeue.
(i) Linear Queue
1. A linear queue is like a straight line in which all elements or instructions stand one behind
the other.
2. Tasks lined up in this queue format are executed in the order of their placement, on a FIFO
(First In First Out)
basis.
3. In a linear queue, a new task is inserted at the end of the list, while a deletion is made at the
front of the list.
4. Allocate new, larger block of memory reflective of the entire (existing) queue and the
queue-size additions.
Circular Queue
1. A circular queue has a circular structure. The last element of this queue is connected with
the first element, thus
completing the circle.
2. Tasks in this format are not essentially executed in the order in which they are sent.
3. In a circular queue, insertions and deletions can happen at any position in the queue.
4. Allocate ONLY the new object or structure-type required.
(ii) A Queue and dequeue
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
A queue is a linear structure implemented in FIFO (First In First Out) manner where insertions
can occur only at
the “rear” end and deletion can occur only at the “front” end whereas Dequeues are the refined
queues in
which elements can be added or removed at either end but not in the middle.
Unsolved exercise
1. Convert the following infix expressions to postfix expressions using stack
(i) A + (B * C) ^ D – (E / F – G)
(ii) A * B / C * D ^ E * G / H
(iii) ((A*B)-((C_D)*E/F)*G
2. Evaluate the following postfix expression E given below; show the contents of the stack
during the evaluation
(i) E= 5,9,+2,/,4,1,1,3,_,*,+ 2
(ii) E= 80,35,20,-,25,5,+,-,*
(iii) E= 30,5,2,^,12,6,/,+,-
(iv) E=15, 3, 2, +, /, 7, + 2, *
3. Define functions in C++ to perform a PUSH and POP operation in a dynamically allocated
stack considering the following :
struct Node
{
int X,Y;
Node *Link;
};
class STACK
{
Node * Top;
public:
STACK( )
{ TOP=NULL;}
void PUSH( );
void POP( );
~STACK( );
};
4. Write a function in C++ to perform a Add and Delete operation in a dynamically allocated
Queue considering the following:
struct node
{
int empno ;
char name[20] ;
float sal ;
Node *Link;
};
STUDY MATERIAL COMPUTER SCIENCE(283) STACK,QUEUE,LINKED IST
By: GAJENDRA S DHAMI
5.class queue
{
int data[10] ;
int front, rear ;
public :
queue( ) { front = - 1 ; rear = - 1 ; }
void add( ) ; //to add an element into the queue
void remove( ) ; //to remove an element from the queue
void Delete(int ITEM( ) ; //to delete all elements which are equal to ITEM
} ;
Complete the class with all function definitions for a circular array Queue. Use another queue
to transfer data temporarily.
6. class stack
{
int data[10] :
int top ;
public :
stack( )
{
top = - 1; }
void push( ) ; //to push an element into the stack
void pop( ) ; //to pop an element from the stack
void Delete(int ITEM) ; //To delete all elements which are equal to ITEM.
} ;
Complete the class with all function definitions. Use another stack to transfer data temporarily.
7. Each node of a STACK contains the following information, in addition to pointer field:
(ii) Pin code of city, (ii) Name of city
Give the structure of node for the linked STACK in question.
TOP is a pointer that points to the topmost node of the STACK. Write the following functions:
(i) PUSH ( ) – To push a node into the STACK, which is allocated dynamically.
(ii) POP () – to remove a node from the STACK, and release the memory.