Drill 3 Data Structures Laboratory

12
DATA STRUCTURES AND ALGORITHMS DRILL 3 STACKS Name:______________________________ Student Number:______________________ Course/Section:________________________ Date of Performance:____________________ Date of Submission:_____________________ GRADE ____________________ Professor

Transcript of Drill 3 Data Structures Laboratory

Page 1: Drill 3 Data Structures Laboratory

DATA STRUCTURES AND ALGORITHMS

DRILL 3 STACKS

Name:______________________________ Student Number:______________________ Course/Section:________________________ Date of Performance:____________________ Date of Submission:_____________________ GRADE

____________________ Professor

Page 2: Drill 3 Data Structures Laboratory

MAPUA INSTITUTE OF TECHNOLOGY SCHOOL OF EE-ECE-CPE

Laboratory Report Rubric

Name of Student:________________________________ Date/Time of Performance:____________ Laboratory Report Title:______________________________________________________________

Criteria Beginner (0-4) Intermediate (5-7) Skilled (8-10) Score Promptness • Report is submitted a

week after the laboratory performance.

• Report is submitted not later than a week after the performance.

• Report is submitted on time.

(over 10)

Accuracy • Results gathered are limited, or are imprecise.

• Incorrect answers to most questions provided in the report

• Results gathered are not that accurate.

• Most of the problems answered are correct.

• Results gathered are accurate.

• All problems are correctly answered.

(over 20)

Discussion of Remarks and Conclusion

• Inappropriate use of words, poor grammar and ideas are not clearly expressed

• Does not point out discussion well

• Appropriate choice of language

• Can express ideas • Discussion was well

versed.

• Use of rich language, excellent grammar, and ideas are expressed precisely

• Discussion was clear and accurate.

(over 20)

Presentation • Untidy • Numerous marks of

erasures • Sheets are either

folded or crampled. • Ink used was not

clear.

• Evident marks of erasures

• Appropriate use of ink. • Clean sheets

• No marks of erasures

• Appropriate use of ink

• Clean and well-organized sheets

(over 10)

Completeness • Most fields are not completely filled.

• Some parts of the report are missing.

• Some fields are not completely filled.

• All sheets are stapled together.

• All fields are completely filled.

• All sheets are stapled together.

(over 10)

Programming Skills • The program does not run

• Logical design of program is disorganized

• Technique used in programming is inaccurate.

• The program runs, but required results are not obtained.

• Logic is not well-organized.

• Use of an effective programming technique/algorithm

• The program runs as expected.

• Organized logic • Use of effective

programming technique

(over 30)

TOTAL /100

______________________________________

Signature over Printed Name of Professor

Page 3: Drill 3 Data Structures Laboratory

I. DISCUSSION STACKS The elementary definition of a stack is an orderly pile arranged in layers. Consider a pile of books. One can place another book in that stack by putting it at the top. To access the book at the bottom of the stack, most likely one needs to remove every book at the top, then continue removing the books until the last book has been recovered. In computer science, the stack is the Abstract Data Type (ADT) for the Last In First Out (LIFO) data structure. Similar to an array, it can have any data type as an element, but is characterized solely by two basic operations: push and pop. Below is the illustration of the two operations:

It is said to be restricted due to the fact that only few operations are allowed in it. Push adds a given node to the top of the stack leaving the previous nodes below. Pop removes and returns the current top node of the stack. With the two fundamental operations, it is clear that elements are removed from the stack in the reverse order to the order of their inclusion in the list. Therefore, the lower elements are those that have been on the stack the longest. If illustrated using simple arrays and pointer notations, note that every element inside your stack can still be accessed using its index, which does not correspond with its property that only the last element can be accessed at a time. The best way to address this situation is to use the concepts of ADT to apply stacks using both arrays and linked list. Here is a basic stack ADT implementation template <class stackADT> class Stacks_ex1 { public: Stacks_ex1<stackADT>(int size) //Post-condition: The array is initialized to size if there exists a value

Page 4: Drill 3 Data Structures Laboratory

{ // passed to the constructor, and initialized to 100 if incorrect size is if (size <=0) //provided { cout<<"Size must be array must be positive! " <<"Creating an array of size 100."; maxsize = 100; } else maxsize = size; stackTop = 0; list = new stackADT[maxsize]; } void InitializeStack() //Post-condition: The top of stack is set to { //a value equal to 0. stackTop = 0; } bool isEmptyStack() const //Post-condition: Return a value if top of stack { //is at its initial value. This denotes that the stack return (stackTop == 0); //is empty } bool isFullStack() //Post-condition: Returns a value if top of stack { //reaches the assigned maximum stack size. This return (stackTop == maxsize); //denotes that the stack is full } void push(stackADT newItem) //Post-condition: Performs the push operation { if (!isFullStack()) { list[stackTop] = newItem; stackTop++; } else cout<<"Cannot add to a full stack"; } void pop() //Post-condition: Performs the pop operation { if(!isEmptyStack()) stackTop--; else cout<<"Cannot remove from an empty stack!\n "; } stackADT top() //Post-condition: Returns the value of the element { //at the top of the stack. Note that to use assert() assert(stackTop!=0); //function, include the cassert library. return list[stackTop - 1]; } private: int stackTop; //the top of stack int maxsize; //the maximum size of stack stackADT *list; //the list to be transformed into a stack }; To implement stacks using arrays, we have the following stack ADT implementation. template<class stacks> struct node

Page 5: Drill 3 Data Structures Laboratory

{ stacks data; node *link; }; template<class stacks> class Stacks_ex3 { private: node<stacks> *stackTop; public: Stacks_ex3<stacks>(); void initialize(); void push(stacks); void pop(); bool isEmptyStack(); stacks top(); }; template<class stacks> Stacks_ex3<stacks>::Stacks_ex3() { stackTop = NULL; } template<class stacks> void Stacks_ex3<stacks>::initialize() { node<stacks> * temp; while(stackTop != NULL) { temp = stackTop; stackTop = stackTop -> link; delete temp; } } template<class stacks> bool Stacks_ex3<stacks>::isEmptyStack() { return (stackTop == NULL); } template<class stacks> void Stacks_ex3<stacks>::push(stacks newItem) { node<stacks> *newNode; newNode = new node<stacks>; newNode -> data = newItem; newNode -> link = stackTop; stackTop = newNode; }

Page 6: Drill 3 Data Structures Laboratory

template<class stacks> void Stacks_ex3<stacks>::pop() { node<stacks> * temp; if (stackTop != NULL) { temp = stackTop; stackTop = stackTop -> link; delete temp; } else cout<<"Stack is empty!"<<endl; } template<class stacks> stacks Stacks_ex3<stacks>::top() { assert(stackTop != NULL); return stackTop -> data; } APPLICATION: Postfix Expression The usual notation for writing arithmetic expressions is called infix notation, in which the operator is between the two operands. For example, in the expression a + b, the operator + is between operands a and b. The postfix expression, on the other hand, is the one that has the notation operand1 operand2 operator. For instance, for infix notation a + b, its postfix representation is a b +. Other examples include the following Infix expression Postfix expression a + b * c a b c * + The order of operation must be taken into consideration. a * b + c a b * c + The first one to be evaluated or converted into postfix is (a + b) * c a b + c * the operands with *, / and % as its operators (from left to (a – b ) * (c + d) a b – c d + * right) and + and – (from left to right). When grouping symbols (a + b) * (c – d / e) + f a b + c d e / - * f + are included, the first to be converted are expressions in

between the grouping symbols

Page 7: Drill 3 Data Structures Laboratory

II. SAMPLE CODES // Stacks_ex1.cpp. Note that one needs to have Stacks_ex1.h which is composed of the program defined by the //stackADT implementation. To successfully see the output of the program, file HighestGPAData.txt should be //created at the specified path. #include "stdafx.h" #include "Stacks_ex1.h" #include<iostream> #include<string> #include<fstream> #include<iomanip> #include<conio.h> using namespace std; int main() { Stacks_ex1 <string> ex1(100); double GPA, highestGPA; string name; ifstream infile; infile.open("C:\\HighestGPAData.txt"); if(!infile) { cout<<"The input file does not exist. " <<"Program Terminates!"<<endl; _getch(); return 0; } cout<<fixed<<showpoint; cout<<setprecision(2); infile>>GPA>>name; highestGPA = GPA; while(infile) { if(GPA > highestGPA) { ex1.InitializeStack(); if(!ex1.isFullStack()) { ex1.push(name); } highestGPA = GPA; } else if (GPA == highestGPA) { if (!ex1.isFullStack()) { ex1.push(name); } else

Page 8: Drill 3 Data Structures Laboratory

{ cout<<"Stack Overflows. " <<"Program terminates!"<<endl; _getch(); return 0; } } infile>>GPA>>name; } cout<<"Highest GPA = "<<highestGPA<<endl; cout<<"The students holding the highest GPA are: "; while (!ex1.isEmptyStack()) { cout<<ex1.top()<<endl; ex1.pop(); } _getch(); } // Stacks_ex2.cpp. Note that one needs to have Stacks_ex1.h which is composed of the program defined by the //stackADT implementation. This sample code will determine the total price of all the items on the list. #include "stdafx.h" #include "Stacks_ex1.h" #include<iostream> #include<conio.h> #include<string> using namespace std; void main() { Stacks_ex2 <float> listOfPrices(5); Stacks_ex2 <string> items(5); float x=0, sum=0; string name; float price; while (x<5) { cout<<"Enter name of Item "<<x+1<<":"; cin>>name; items.push(name); cout<<"Enter price:"; cin>>price; listOfPrices.push(price); x++; } x = 0; while(x<5) { sum = sum + listOfPrices.top(); listOfPrices.pop(); x++; } cout<<"The sum of all the prices in the list is " <<sum;

Page 9: Drill 3 Data Structures Laboratory

_getch(); } //Stacks_ex3.cpp: This one requires the user to have the linked list implementation of stacks as an ADT at Stacks_ex3.h //stated above. This will convert an infix notation input into its corresponding postfix notation (disregarding the grouping //symbols as well as the MDAS rule). #include "stdafx.h" #include "Stacks_ex3.h" #include<iostream> #include<conio.h> #include<string> #include<vector> using namespace std; void main() { Stacks_ex3<char> operation; char temp = '$'; cout<<"Enter expression:"; char *st = new char[100]; char *stringtemp = new char[100]; gets(st); int x=0, y=0, z; while(st[x]!= NULL) { if (st[x] == '*' || st[x] == '+' || st[x] == '-' || st[x] == '//' || st[x] == '%') { temp = st[x]; } else { if (temp=='$') { operation.push(st[x]); } else { z=0; while (!operation.isEmptyStack()) { stringtemp[z] = operation.top(); operation.pop(); z++; } operation.push(temp); operation.push(st[x]); while(z>0) { operation.push(stringtemp[z-1]); z--; } temp = '$'; } } x++; }

Page 10: Drill 3 Data Structures Laboratory

while (!operation.isEmptyStack()) { cout<<operation.top(); operation.pop(); } _getch(); }

III. PROGRAMMING EXERCISE 1. Modify the application from sample code 3 wherein the parentheses () and MDAS rule will be included in the expression to denote that whatever is placed inside the parentheses should be evaluated first, and that multiplication, division and modulo is to be considered first before addition and subtraction. For instance, Infix notation: 8 * (9 – 5) + ((2 / 5)% 6) Postfix notation: 8 9 5 - *2 5 / 6 % + 2. Write a program that uses a stack to convert a binary number into any preferred equivalent base number (range from base 3 up to base 16). 3. Create a file named StackOfWords.txt that contains 15 five-letter words of your own choices separated each by a new line and are arranged alphabetically. Continue by doing a program that will insert a word from the file to the stack if there are more than two vowels present in each word. Display the words placed inside the stack in alphabetical manner. IV. QUESTIONS 1. If the content of file HighestGPAData.txt is from Sample Code 1 is as follows: 3.5 Bill 3.6 John 2.7 Lisa 3.9 Kathy 3.4 Jason 3.9 David 3.4 Jack What is the output of the program? _______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

2. Why are stacks considered as restricted versions of arrays and linked lists? _______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

3. If Stacks_ex1 class is implemented with the following object: Stacks_ex1 <int> stack; int x, y; what is the output of the following segment of code: x = 4; y = 5;

Page 11: Drill 3 Data Structures Laboratory

stack.push(6); stack.push(y-x); stack.push(x%7); y = stack.top(); stack.push(x+y); stack.pop(); stack.push(3); x = stack.top(); cout≪”x = ” ≪ x ≪ endl; cout≪”y = ” ≪ y ≪ endl; while (!stack.isEmptyStack()) { cout≪stack.top()≪endl;

stack.pop(); } _______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________ 4. Convert the following into its corresponding infix / postfix expression:

INFIX POSTFIX (A + B) * (C + D) – E A + B * (C + D) – E / F * G + H A B – C – D * A B + C D - / E F G * % *

5. Evaluate the following postfix expressions (show solution in a separate sheet): a. 8 2 + 3 * 1 6 4 / - = b. 3 5 6 * + 1 – 8 2 / + = c. 70 14 4 5 15 3 / * - - / 6 + = 6. Function isFullStack() is hardly applied to linked implementations of stacks. Why is this so? _______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________

Page 12: Drill 3 Data Structures Laboratory

V. REMARKS AND CONCLUSION ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________ ______________________________________________________________________________