LAB ASSIGNMENT Please Use C++ and do it from scratch. Thanks in advance. Task 1:
ID: 3802295 • Letter: L
Question
LAB ASSIGNMENT Please Use C++ and do it from scratch.
Thanks in advance.
Task 1:
Implement a Stack on a char [] array. Do not use ::stack:: class from the STD library for this example.
The user will input a string and the program will output the string backwards. Displaying correct Stack implementation.
Utilize the conventional static methods as needed.
push()
pop()
empty()
peek()
peek()
Sample Execution
Please input String:
happy
yppah
Task 2:
Implement a stack using a vector or the STD ::stack:: class
Note the difference in what it takes to implement using a static char[] array vs a vector or the STD ::stack:: class
The user will input a string and the program will output the string backwards. Displaying correct Stack implementation.
Utilize the conventional static methods as needed.
push()
pop()
empty()
peek()
peek()
Sample Execution
Please input String:
happy
yppah
Explanation / Answer
1.
#include<iostream>
using namespace::std;
struct stack {
char *data;
int top;
};
int main() {
void push(char, stack*);
char pop(stack*);
int empty(stack*);
stack stk1;
string input;
stk1.data = new char[50];
stk1.top = -1;
cout<<"Please input string: ";
cin>>input;
for (int i=0; i<input.length(); ++i)
push(input.at(i),&stk1);
while (empty(&stk1) == 0)
cout<<pop(&stk1);
return 0;
}
void push(char ch, stack* s) {
s->data[++(s->top)] = ch;
}
char pop (stack* s) {
return s->data[(s->top)--];
}
int empty(stack* s) {
return (s->top==-1)?1:0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.