Stack
Stack
int sum = 0;
while (!record.empty()) {
sum += record.top();
record.pop();
}
return sum;
}
Bài 2
void push(T item) {
list.add(item);
}
T pop() {
T topItem = list.get(list.size() - 1);
list.removeAt(list.size() - 1);
return topItem;
}
T top() {
return list.get(list.size() - 1);
}
bool empty() {
return list.empty();
}
int size() {
return list.size();
}
void clear() {
list.clear();
}
Bài 3
vector<int> nextGreater(const vector<int>& nums) {
int n = nums.size();
vector<int> result(n, -1);
stack<int> stk;
stk.push(i);
}
return result;
}
Bài 4
int evaluatePostfix(string expression){
stack<int> operandStack;
istringstream iss(expression);
string token;
while (iss >> token) {
// Check if the token is an operator
if (token == "+" || token == "-" || token == "*" || token == "/") {
int result;
if (token == "+")
result = operand1 + operand2;
else if (token == "-")
result = operand1 - operand2;
else if (token == "*")
result = operand1 * operand2;
else if (token == "/")
result = operand1 / operand2;
operandStack.push(result);
} else {
int operand = stoi(token);
operandStack.push(operand);
}
}
return operandStack.top();
}
Bài 5
bool canEatFood(int maze[5][5], int fx, int fy){
stack<node> pathStack;
vector<vector<bool>> visited(5, vector<bool>(5, false));
while (!pathStack.empty()) {
node current = pathStack.top();
pathStack.pop();
int x = current.x;
int y = current.y;
int dir = current.dir;
visited[x][y] = true;
if (x == fx && y == fy)
return true;
if (newX >= 0 && newX < 5 && newY >= 0 && newY < 5 && maze[newX][newY]
== 1 && !visited[newX][newY]) {
node next(newX, newY);
next.dir = 0; // Reset direction for the new node
pathStack.push(next);
current.dir = dir + 1;
pathStack.push(current);
break;
}
dir++;
}
}
Bài 6
string removeDuplicates(string S){
stack<char> charStack;
for (char ch : S) {
if (!charStack.empty() && charStack.top() == ch) {
charStack.pop();
} else {
charStack.push(ch);
}
}
string result;
while (!charStack.empty()) {
result = charStack.top() + result;
charStack.pop();
}
return result;
}
Bài 7
vector<int> stock_span(const vector<int> &ns) {
vector<int> spans;
stack<pair<int, int>> stk;
spans.push_back(span);
stk.push({ span, ns[i] });
}
return spans;
}
Bài 8
bool isValidParentheses (string s){
stack<char> parenthesesStack;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
parenthesesStack.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (parenthesesStack.empty()) {
return false;
}
if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}'
&& top != '{')) {
return false;
}
}
}
return parenthesesStack.empty();