DATA STRUCTURES AND ALGORITHMS

DRILL 3

STACKS

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

____________________
Professor

GRADE

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) Promptness • Report is submitted a week after the laboratory performance. • Report is submitted not later than a week after the performance. All sheets are stapled together. • Evident marks of erasures Appropriate use of ink. Clean sheets • Most fields are not completely filled. No marks of erasures Appropriate use of ink Clean and wellorganized sheets (over 20) (over 10) Completeness • • • • All fields are completely filled. • Some fields are not completely filled. but required results are not obtained. • Appropriate choice of language Can express ideas Discussion was well versed. • The program runs. or are imprecise. (over 10) Programming Skills • • • • • • • The program runs as expected. Logic is not wellorganized. Accuracy • Results gathered are limited. poor grammar and ideas are not clearly expressed Does not point out discussion well Untidy Numerous marks of erasures Sheets are either folded or crampled. Inappropriate use of words. Incorrect answers to most questions provided in the report • Results gathered are not that accurate. Organized logic Use of effective programming technique (over 30) TOTAL /100 ______________________________________ Signature over Printed Name of Professor . and ideas are expressed precisely Discussion was clear and accurate. Some parts of the report are missing. • Report is submitted on time. • Results gathered are accurate. Ink used was not clear. Use of an effective programming technique/algorithm • • Discussion of Remarks and Conclusion • • Presentation • • • • Score (over 10) • • (over 20) • • • • • • • • Use of rich language. All problems are correctly answered. excellent grammar. Most of the problems answered are correct. • The program does not run Logical design of program is disorganized Technique used in programming is inaccurate. All sheets are stapled together.

With the two fundamental operations. To access the book at the bottom of the stack. the stack is the Abstract Data Type (ADT) for the Last In First Out (LIFO) data structure. Therefore. If illustrated using simple arrays and pointer notations. In computer science. Push adds a given node to the top of the stack leaving the previous nodes below.I. most likely one needs to remove every book at the top. The best way to address this situation is to use the concepts of ADT to apply stacks using both arrays and linked list. but is characterized solely by two basic operations: push and pop. then continue removing the books until the last book has been recovered. it is clear that elements are removed from the stack in the reverse order to the order of their inclusion in the list. Consider a pile of books. 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 . One can place another book in that stack by putting it at the top. note that every element inside your stack can still be accessed using its index. Pop removes and returns the current top node of the stack. Similar to an array. 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. the lower elements are those that have been on the stack the longest. DISCUSSION STACKS The elementary definition of a stack is an orderly pile arranged in layers. which does not correspond with its property that only the last element can be accessed at a time. it can have any data type as an element.

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

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

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

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

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

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

If the content of file HighestGPAData.top(). If Stacks_ex1 class is implemented with the following object: Stacks_ex1 <int> stack. QUESTIONS 1. 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).6 John 2. Why are stacks considered as restricted versions of arrays and linked lists? _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ 3. IV.isEmptyStack()) { cout<<operation. Infix notation: 8 * (9 – 5) + ((2 / 5)% 6) Postfix notation: 8 9 5 . For instance. III.txt is from Sample Code 1 is as follows: 3. 3. 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.pop().5 Bill 3. PROGRAMMING EXERCISE 1. int x. 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. operation.7 Lisa 3.} while (!operation.4 Jason 3.9 Kathy 3.4 Jack What is the output of the program? _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ 2. and that multiplication. y.*2 5 / 6 % + 2. what is the output of the following segment of code: x = 4. division and modulo is to be considered first before addition and subtraction. Display the words placed inside the stack in alphabetical manner. y = 5. } _getch(). 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.9 David 3. .

stack.top()≪endl.stack. stack. 8 2 + 3 * 1 6 4 / . Function isFullStack() is hardly applied to linked implementations of stacks. while (!stack. Convert the following into its corresponding infix / postfix expression: INFIX POSTFIX (A + B) * (C + D) – E A + B * (C + D) – E / F * G + H AB–C–D* AB+CD-/ EFG*%* 5. stack. } _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ 4. y = stack. cout≪”y = ” ≪ y ≪ endl. 3 5 6 * + 1 – 8 2 / + = c.= b.. stack.push(x%7).push(x+y).pop(). stack.push(3). x = stack.isEmptyStack()) { cout≪stack.top(). stack. 70 14 4 5 15 3 / * ./ 6 + = 6. Evaluate the following postfix expressions (show solution in a separate sheet): a.pop().push(6).top().push(y-x). cout≪”x = ” ≪ x ≪ endl. Why is this so? _____________________________________________________________________________________ _____________________________________________________________________________________ _____________________________________________________________________________________ .

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