0% found this document useful (0 votes)
8 views20 pages

Stack - Xem lại lần làm thử - BK-LMS

The document details a series of programming tasks related to stack implementations and operations, including methods for a Stack class and a baseball scoring system. Each task includes example inputs and expected outputs, with successful test results confirming the correctness of the solutions. The document also covers duplicate removal from strings and finding the next greater element in an array, all achieving full marks in the assessments.

Uploaded by

tronghien5111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views20 pages

Stack - Xem lại lần làm thử - BK-LMS

The document details a series of programming tasks related to stack implementations and operations, including methods for a Stack class and a baseball scoring system. Each task includes example inputs and expected outputs, with successful test results confirming the correctness of the solutions. The document also covers duplicate removal from strings and finding the next greater element in an array, all achieving full marks in the assessments.

Uploaded by

tronghien5111
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Trạng thái Đã xong


Bắt đầu vào lúc Thứ Hai, 21 tháng 10 2024, 3:12 PM
Kết thúc lúc Thứ Năm, 24 tháng 10 2024, 11:59 PM
Thời gian thực 3 Các ngày 8 giờ
hiện
Điểm 8,00/8,00
Điểm 10,00 trên 10,00 (100%)

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 1/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 1
Đúng

Đạt điểm 1,00 trên 1,00

Implement all methods in class Stack with template type T. The description of each method is written as comment in frame
code.

#ifndef STACK_H
#define STACK_H
#include "DLinkedList.h"
template<class T>
class Stack {
protected:
DLinkedList<T> list;
public:
Stack() {}
void push(T item) ;
T pop() ;
T top() ;
bool empty() ;
int size() ;
void clear() ;
};

#endif

You can use all methods in class DLinkedList without implementing them again. The description of class DLinkedList is written as
comment in frame code.

template <class T>


class DLinkedList
{
public:
class Node; //forward declaration
protected:
Node* head;
Node* tail;
int count;
public:
DLinkedList() ;
~DLinkedList();
void add(const T& e);
void add(int index, const T& e);
T removeAt(int index);
bool removeItem(const T& removeItem);
bool empty();
int size();
void clear();
T get(int index);
void set(int index, const T& e);
int indexOf(const T& item);
bool contains(const T& item);
};

For example:

Test Result

Stack<int> stack; 1 0
cout << stack.empty() << " " << stack.size();

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 2/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Result

Stack<int> stack; 8

int item[] = { 3, 1, 4, 5, 2, 8, 10, 12 };


for (int idx = 0; idx < 8; idx++) stack.push(item[idx]);

assert(stack.top() == 12);

stack.pop();
stack.pop();

cout << stack.top();

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ void push(T item) {


2 // TODO: Push new element into the top of the stack
3 list.add(item);
4 }
5
6 ▼ T pop() {
7 // TODO: Remove an element on top of the stack
8 return list.removeAt(list.size()-1);
9 }
10
11 ▼ T top() {
12 // TODO: Get value of the element on top of the stack
13 return list.get(list.size()-1);
14 }
15
16 ▼ bool empty() {
17 // TODO: Determine if the stack is empty
18 return (list.empty());
19 }
20
21 ▼ int size() {
22 // TODO: Get the size of the stack
23 return list.size();
24 }
25
26 ▼ void clear() {
27 // TODO: Clear all elements of the stack
28 list.clear();
29 }

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 3/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 Stack<int> stack; 1 0 1 0 
cout << stack.empty() << " " << stack.size();

 Stack<int> stack; 8 8 

int item[] = { 3, 1, 4, 5, 2, 8, 10, 12 };


for (int idx = 0; idx < 8; idx++) stack.push(item[idx]);

assert(stack.top() == 12);

stack.pop();
stack.pop();

cout << stack.top();

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 4/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 2
Đúng

Đạt điểm 1,00 trên 1,00

You are keeping score for a basketball game with some new rules. The game consists of several rounds, where the scores of past rounds may
affect future rounds' scores.

At the beginning of the game, you start with an empty record. You are given a list of strings ops, where ops[i] is the operation you must apply
to the record, with the following rules:

A non-negative integer x (from 0 to 9) - record a new score of x


'+' - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.
'D' - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.
'C' - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.

Finally, return the sum of all scores in the record.


For example:
ops = "52CD+"

'5' - add to the record. Record now is [5]


'2' - add to the record. Record now is [5,2]
'C' - invalid the previous score (2). Record now is [5]
'D' - Record new score that is double of previous score (5*2). Record now is [5,10]
'+' - Record a new score that is the sum of the previous two scores. Record now is [5,10,15]

Return the sum: 5+10+15 = 30

For example:

Test Result

cout << baseballScore("52CD+"); 30

cout << baseballScore("524CD9++"); 55

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int baseballScore(string ops){


2 /*TODO*/
3 stack<int> stack;
4 ▼ for (int i = 0; i <(int)ops.size(); ++i){
5 if (ops[i] >= '0' && ops[i] <= '9') stack.push(ops[i] - '0');
6 if (ops[i] == 'C') stack.pop();
7 ▼ if (ops[i] == 'D') {
8 int val = stack.top();
9 stack.push(val*2);
10 }
11 ▼ if (ops[i] == '+'){
12 int top1 = stack.top();
13 stack.pop();
14 int top2 = stack.top();
15 stack.push(top1);
16 stack.push(top1 + top2);
17 }
18 // cout<<stack.top()<<" ";
19 }
20 int s = 0;
21 ▼ while (!stack.empty()){
22 s += stack.top();
23 // cout<<stack.top()<<" ";
24 stack.pop(); 
25 }
26 return s;
27 }

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 5/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 cout << baseballScore("52CD+"); 30 30 

 cout << baseballScore("524CD9++"); 55 55 

 cout << baseballScore("5C4C2C11+D3"); 11 11 

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 6/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 3
Đúng

Đạt điểm 1,00 trên 1,00

Given an array nums[] of size N having distinct elements, the task is to find the next greater element for each element of
the array
Next greater element of an element in the array is the nearest element on the right which is greater than the current
element.
If there does not exist a next greater of a element, the next greater element for it is -1

Note: iostream, stack and vector are already included

Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9

Example 1:
Input:
nums = {15, 2, 4, 10}
Output:
{-1, 4, 10, -1}

Example 2:
Input:
nums = {1, 4, 6, 9, 6}
Output:
{4, 6, 9, -1, -1}

For example:

Test Input Result

int N; 4 -1 4 10 -1
cin >> N; 15 2 4 10
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

int N; 5 4 6 9 -1 -1
cin >> N; 1 4 6 9 6
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

Answer: (penalty regime: 0 %)

Reset answer

1 // iostream, stack and vector are included


2
3 ▼ vector<int> nextGreater(vector<int>& arr){
4 vector<int> value(arr.size(), -1);
5 ▼ for (size_t i = 0; i <arr.size(); ++i){
6 ▼ for (size_t j = i +1; j <arr.size(); ++j){ 
7 ▼ if (arr[j] > arr[i]){
8 value[i] = arr[j];
9 break;
10 }
11 }
12 }
13 return value;
14 }
https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 7/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS
14 }

Test Input Expected Got

 int N; 4 -1 4 10 -1 -1 4 10 -1 
cin >> N; 15 2 4 10
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

 int N; 5 4 6 9 -1 -1 4 6 9 -1 -1 
cin >> N; 1 4 6 9 6
vector<int> nums(N);
for(int i = 0; i < N; i++) cin >> nums[i];
vector<int> greaterNums = nextGreater(nums);
for(int i : greaterNums)
cout << i << ' ';
cout << '\n';

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 8/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 4
Đúng

Đạt điểm 1,00 trên 1,00

Given a string S of characters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made.

Included libraries: vector, list, stack

For example:

Test Result

cout << removeDuplicates("abbaca"); ca

cout << removeDuplicates("aab"); b

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ string removeDuplicates(string S){


2 /*TODO*/
3 vector<char> ans(S.size(), ' ');
4 int top = 0;
5 ▼ for (auto v : S){
6 if (v == ans[top])
7 --top;
8 else
9 ans[++top] = v;
10 }
11 string s = "";
12 for (int i = 1; i <=top; ++i)
13 s +=ans[i];
14 return s;
15 }

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 9/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 cout << removeDuplicates("abbaca"); ca ca 

 cout << removeDuplicates("aab"); b b 

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 10/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 5
Đúng

Đạt điểm 1,00 trên 1,00

Given a string s containing just the characters '(', ')', '[', ']', '{', and '}'. Check if the input string is valid based on following
rules:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.

For example:
String "[]()" is a valid string, also "[()]".
String "[])" is not a valid string.

Your task is to implement the function


bool isValidParentheses (string s){
/*TODO*/
}

Note: The library stack of C++ is included.

For example:

Test Result

cout << isValidParentheses("[]"); 1

cout << isValidParentheses("[]()"); 1

cout << isValidParentheses("[)"); 0

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ bool isValidParentheses (string s){


2 stack<char> st;
3
4 ▼ for(int i=0;i<(int)s.size();++i) {
5 char c= s[i];
6 // if (c != '(' && c != ')' && c != '[' && c != ']' && c != '{' && c != '}')
7 if (c == '(' || c == '[' || c == '{') st.push(c);
8 ▼ else {
9 if (st.empty()) return false;
10 if (c == ')' && st.top() == '(') st.pop();
11 else if (c == ']' && st.top() == '[') st.pop();
12 else if (c == '}' && st.top() == '{') st.pop();
13 else return false;
14 }
15 }
16
17 if (st.empty())
18 return true;
19 return false;
20 /*TODO*/
21 }

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 11/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 cout << isValidParentheses("[]()"); 1 1 

 cout << isValidParentheses("[)"); 0 0 

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 12/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 6
Đúng

Đạt điểm 1,00 trên 1,00

A Maze is given as 5*5 binary matrix of blocks and there is a rat initially at the upper left most block i.e., maze[0][0] and the
rat wants to eat food which is present at some given block in the maze (fx, fy). In a maze matrix, 0 means that the block is
a dead end and 1 means that the block can be used in the path from source to destination. The rat can move in any
direction (not diagonally) to any block provided the block is not a dead end.

Your task is to implement a function with following prototype to check if there exists any path so that the rat can reach the
food or not:
bool canEatFood(int maze[5][5], int fx, int fy);

Template:

#include <iostream> #include <fstream> #include <string> #include <cstring> #include <stack> #include <vector> using
namespace std;

class Node { public: int x, y; int dir; node(int i, int j) { x = i; y = j; // Initially direction // set to 0 dir = 0; } };
Some suggestions: - X : x coordinate of the node - Y : y coordinate of the node - dir : This variable will be used to tell which
all directions we have tried and which to choose next. We will try all the directions in anti-clockwise manner starting from
up.

If dir=0 try up direction.


If dir=1 try left direction.
If dir=2 try down direction.
If dir=3 try right direction.

For example:

Test Result

// Maze matrix 1
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 1 },
{ 0, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 0 },
{ 1, 0, 0, 1, 0 }
};

// Food coordinates
int fx = 1, fy = 4;

cout << canEatFood(maze, fx, fy);

// Maze matrix 1
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 0 }
};

// Food coordinates
int fx = 2, fy = 3;

cout << canEatFood(maze, fx, fy);

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 13/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS
Answer: (penalty regime: 0 %)

Reset answer

1
2 ▼ class node{
3 public:
4 int x,y;
5
6 node(int x,int y) : x(x),y(y){}
7 };
8
9 ▼ bool isSafe( int maze[5][5], vector<vector<bool>> &visited, int X,int Y){
10 // Check if not a block or outmaze or visited
11 if (X >=0 && Y >=0 && X <=4 && Y <=4)
12 return (!visited[X][Y] && (maze[X][Y] == 1));
13 else return false;
14 // return ( && !visited[X][Y]);
15 }
16
17 ▼ bool canEatFood(int maze[5][5], int fx, int fy){
18 /*TODO*/
19 vector<vector<bool>> visited (5, vector<bool>(5, false)); // Phải khởi tạo ở bên
20
21 int moveX[] = {-1,0,1,0};
22 int moveY[] = {0,-1,0,1};
23 stack<node> s;
24 s.push({0,0}); // = node temp(0,0); s.push(temp); ??
25 visited[0][0] = true;
26 ▼ while (!s.empty()){
27 node p = s.top();
28 s.pop();
29
30 if (p.x == fx && p.y == fy) return true;
31
32 ▼ for (int i = 0;i < 4;++i){
33 int newX= p.x + moveX[i], newY = p.y + moveY[i];
34 //cout<<visited[p.x][p.y]<<'\n';
35 // cout<<newX<<" "<<newY<<" "<<(newX >=0 && newY >=0 && newX <=4 && newY
36 ▼ if (isSafe(maze,visited,newX,newY)) {
37 node temp(newX,newY);
38 s.push(temp);
39 visited[newX][newY] = true;
40 }
41 }
42 // cout<< p.x<<" "<<p.y<<'\n';
43 }
44 return false;
45
46 }
47
48

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 14/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 // Maze matrix 1 1 
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 1 },
{ 0, 1, 0, 1, 1 },
{ 1, 1, 1, 1, 0 },
{ 1, 0, 0, 1, 0 }
};

// Food coordinates
int fx = 1, fy = 4;

cout << canEatFood(maze, fx, fy);

 // Maze matrix 1 1 
int maze[5][5] = {
{ 1, 0, 1, 1, 0 },
{ 1, 1, 1, 0, 0 },
{ 0, 1, 0, 1, 1 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 1, 1, 0 }
};

// Food coordinates
int fx = 2, fy = 3;

cout << canEatFood(maze, fx, fy);

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 15/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 7
Đúng một phần

Đạt điểm 1,00 trên 1,00

Vietnamese version:

Bài toán stock span là một bài toán về chủ đề kinh tế tài chính, trong đó ta có thông tin về giá của một cổ phiếu qua từng
ngày. Mục tiêu của bài toán là tính span của giá cổ phiếu ở từng ngày.

Span của giá cổ phiếu tại ngày thứ i (ký hiệu là Si) được định nghĩa là số ngày liên tục nhiều nhất liền trước ngày thứ i có
giá cổ phiếu thấp hơn, cộng cho 1 (cho chính nó).

Ví dụ, với chuỗi giá cổ phiếu là [100, 80, 60, 70, 60, 75, 85].

1. Ngày thứ 0 không có ngày liền trước nên S0 bằng 1.


2. Ngày thứ 1 có giá nhỏ hơn giá ngày thứ 0 nên S1 bằng 1.
3. Ngày thứ 2 có giá nhỏ hơn giá ngày thứ 1 nên S2 bằng 1.
4. Ngày thứ 3 có giá lớn hơn giá ngày thứ 2 nên S3 bằng 2.
5. Ngày thứ 4 có giá nhỏ hơn giá ngày thứ 3 nên S4 bằng 1.
6. Ngày thứ 5 có giá lớn hơn giá ngày thứ 4, 3, 2 nên S5 bằng 4.
7. Ngày thứ 6 có giá lớn hơn giá ngày thứ 5, 4, 3, 2, 1 nên S6 bằng 6.

Kết quả sẽ là [1, 1, 1, 2, 1, 4, 6].

Yêu cầu. Viết chương trình tính toán chuỗi span từ chuỗi giá cổ phiếu từ đầu vào.

Input. Các giá trị giá cổ phiếu, cách nhau bởi các ký tự khoảng trắng, được đưa vào standard input.
Output. Các giá trị span, cách nhau bởi một khoảng cách, được xuất ra standard ouput.

(Nguồn: Geeks For Geeks)

=================================

Phiên bản tiếng Anh:

The stock span problem is a financial problem where we have a series of daily price quotes for a stock and we need to
calculate the span of the stock’s price for each day.

The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the
given day, for which the price of the stock on the current day is less than its price on the given day, plus 1 (for itself).

For example: take the stock's price sequence [100, 80, 60, 70, 60, 75, 85]. (See image above)

The given input span for 100 will be 1, 80 is smaller than 100 so the span is 1, 60 is smaller than 80 so the span is 1, 70 is
greater than 60 so the span is 2 and so on.

Hence the output will be [1, 1, 1, 2, 1, 4, 6].


Requirement. Write a program to calculate the spans from the stock's prices.

Input. A list of whitespace-delimited stock's prices read from standard input.

Output. A list of space-delimited span values printed to standard output.

(Source: Geeks For Geeks)


https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 16/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS
For example:

Input Result

100 80 60 70 60 75 85 1 1 1 2 1 4 6

10 4 5 90 120 80 1 1 2 4 5 1

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ vector<int> stock_span(const vector<int>& ns) {


2 // STUDENT ANSWER
3 stack<int> stack;
4 stack.push(0);
5
6 vector<int> ans(ns.size());
7 ans[0] = 1;
8
9 ▼ for (int i = 1;i <(int)ns.size(); ++i){
10 while (!stack.empty() && ns[stack.top()] <= ns[i] )
11 stack.pop();
12 ans[i] = (stack.empty()) ? (i+1) : (i - stack.top());
13
14 stack.push(i);
15 }
16 return ans;
17 }
18 ▼ // vector<int> stock_span(const vector<int>& ns) {
19 // // STUDENT ANSWER
20 // int n= ns.size();
21
22 // vector<int> a;
23 // a.push_back(1e9);
24
25 // for(int v : ns) a.push_back(v);
26
27
28 // vector<int> d(n), ans;
29 // int top= 0;
30 ▼ // for(int i=1;i<=n;++i) {
31 // while(a[d[top]] < a[i]) --top;
32 // ans.push_back(i - d[top]);
33
34 // d[++top]= i;
35 // }
36
37
38 // return ans;
39 // }
40

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 17/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Input Expected Got

 100 80 60 70 60 75 85 1 1 1 2 1 4 6 1 1 1 2 1 4 6 

 10 4 5 90 120 80 1 1 2 4 5 1 1 1 2 4 5 1 

Your code failed one or more hidden tests.

Đúng một phần



Marks for this submission: 0,30/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 18/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Câu hỏi 8
Đúng

Đạt điểm 1,00 trên 1,00

Given string S representing a postfix expression, the task is to evaluate the expression and find the final value. Operators
will only include the basic arithmetic operators like *, /, + and -.

Postfix expression: The expression of the form “a b operator” (ab+) i.e., when a pair of operands is followed by an
operator.
For example: Given string S is "2 3 1 * + 9 -". If the expression is converted into an infix expression, it will be 2 + (3 * 1) – 9 = 5 –
9 = -4.
Requirement: Write the function to evaluate the value of postfix expression.

For example:

Test Result

cout << evaluatePostfix("2 3 1 * + 9 -"); -4

cout << evaluatePostfix("100 200 + 2 / 5 * 7 +"); 757

Answer: (penalty regime: 0 %)

Reset answer

1 ▼ int evaluatePostfix(string expr){


2 /*TODO*/
3 stack<int> stack;
4 int s = 0;
5 ▼ for (size_t i = 0; i <expr.size(); ++i){
6 int top1,top2;
7 ▼ if (expr[i] >= '0' && expr[i] <= '9'){
8 s = s*10 + (expr[i] - '0'); // KHÁC NHAU NHA
9
10 }
11 ▼ else if (expr[i] == ' '){
12 ▼ if (s !=0) {
13 stack.push(s);
14 s = 0;
15 }
16 }
17 ▼ else if (expr[i] == '*'){
18 top1 = stack.top(); stack.pop();
19 top2 = stack.top(); stack.pop();
20 stack.push(top1*top2);
21 }
22 ▼ else if (expr[i] == '/'){
23 top1 = stack.top(); stack.pop();
24 top2 = stack.top(); stack.pop();
25 stack.push(top2/top1);
26 }
27 ▼ else if (expr[i] == '+'){
28 top1 = stack.top(); stack.pop();
29 top2 = stack.top(); stack.pop();
30 stack.push(top1+top2);
31 }
32 ▼ else if (expr[i] == '-'){
33 top1 = stack.top(); stack.pop();
34 top2 = stack.top(); stack.pop();
35 stack.push(top2-top1);
36 }
37 // cout<< stack.top()<<" ";
38 } 
39 return stack.top();
40 }

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 19/20
10/29/24, 1:18 PM Stack: Xem lại lần làm thử | BK-LMS

Test Expected Got

 cout << evaluatePostfix("2 3 1 * + 9 -"); -4 -4 

 cout << evaluatePostfix("100 200 + 2 / 5 * 7 +"); 757 757 

Passed all tests! 

Đúng
Marks for this submission: 1,00/1,00.

https://lms.hcmut.edu.vn/mod/quiz/review.php?attempt=4602652&cmid=440863 20/20

You might also like