數據結構 棧和隊列的應用

在昨天分享了有關棧和隊列的基礎知識和基本操作后,今天來分享一些有關棧和隊列的應用

棧和隊列的應用

  1. 刪除字符串中的所有相鄰重復項
#include <iostream>
#include <stack>
using namespace std;
string remove(string S)
{stack<char> charStack;for (int i = 0; i < S.length(); ++i){char c=S[i];if (!charStack.empty() && charStack.top() == c){charStack.pop();}else{charStack.push(c);}}string result;while (!charStack.empty()){result = charStack.top() + result;charStack.pop();}return result;
}
int main()
{string in;cin >> in;string result = remove(in);cout<<result;return 0;
}
  1. 括號匹配問題(類比20.LeetCode 有效的括號)
#include <iostream>
#include <stack>
#include <string>using namespace std;bool match(string input)
{stack<char> s;for (int i = 0; i < input.length(); i++){char bracket = input[i];if (bracket == '(' || bracket == '{' || bracket == '['){s.push(bracket);}else if (bracket == ')' || bracket == '}' || bracket == ']'){if (s.empty()){return false;}char top = s.top();s.pop();if ((bracket == ')' && top != '(') || (bracket == '}' && top != '{') || (bracket == ']' && top != '[')){return false;}}}return s.empty();
}int main()
{string input;cin >> input;if (match(input)){cout << "yes" << endl;}else{cout << "no" << endl;}return 0;
}
  1. 計算后綴表達式
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <cstdlib>using namespace std;int customAtoi(const string &str)
{int result = 0;int sign = 1;size_t i = 0;if (str[0] == '-'){sign = -1;i = 1;}for (; i < str.length(); i++){if (isdigit(str[i])){result = result * 10 + (str[i] - '0');}else{cerr << "Error: Invalid character in input: " << str[i] << endl;std::exit(1);}}return result * sign;
}bool isOperator(const string &token)
{return (token == "+" || token == "-" || token == "*");
}int evaluatePostfixExpression()
{stack<int> operands;string token;while (cin >> token){if (token == "#"){break;}if (!isOperator(token)){operands.push(customAtoi(token));}else{int operand2 = operands.top();operands.pop();int operand1 = operands.top();operands.pop();int result;if (token == "+"){result = operand1 + operand2;}else if (token == "-"){result = operand1 - operand2;}else if (token == "*"){result = operand1 * operand2;}operands.push(result);}}if (!operands.empty()){return operands.top();}cerr << "Error: Invalid expression." << endl;std::exit(1);
}int main()
{int result = evaluatePostfixExpression();cout << result << endl;return 0;
}
  1. 表達式求值
#include <iostream>
#include <stack>
#include <string>
#include <cctype>using namespace std;int precedence(char op)
{if (op == '+' || op == '-'){return 1;}else if (op == '*' || op == '/'){return 2;}return 0;
}int evaluateExpression(const string &expression)
{stack<int> values;stack<char> operators;for (size_t i = 0; i < expression.length(); i++){if (isspace(expression[i])){continue;}else if (isdigit(expression[i])){int num = 0;while (i < expression.length() && isdigit(expression[i])){num = num * 10 + (expression[i] - '0');i++;}i--;values.push(num);}else if (expression[i] == '('){operators.push(expression[i]);}else if (expression[i] == ')'){while (!operators.empty() && operators.top() != '('){char op = operators.top();operators.pop();int operand2 = values.top();values.pop();int operand1 = values.top();values.pop();if (op == '+'){values.push(operand1 + operand2);}else if (op == '-'){values.push(operand1 - operand2);}else if (op == '*'){values.push(operand1 * operand2);}else if (op == '/'){values.push(operand1 / operand2);}}operators.pop(); }else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/'){while (!operators.empty() && operators.top() != '(' && precedence(operators.top()) >= precedence(expression[i])){char op = operators.top();operators.pop();int operand2 = values.top();values.pop();int operand1 = values.top();values.pop();if (op == '+'){values.push(operand1 + operand2);}else if (op == '-'){values.push(operand1 - operand2);}else if (op == '*'){values.push(operand1 * operand2);}else if (op == '/'){values.push(operand1 / operand2);}}operators.push(expression[i]);}}while (!operators.empty()){char op = operators.top();operators.pop();int operand2 = values.top();values.pop();int operand1 = values.top();values.pop();if (op == '+'){values.push(operand1 + operand2);}else if (op == '-'){values.push(operand1 - operand2);}else if (op == '*'){values.push(operand1 * operand2);}else if (op == '/'){values.push(operand1 / operand2);}}return values.top();
}int main()
{string expression;getline(cin, expression);int result = evaluateExpression(expression);cout << result << endl;return 0;
}
  1. 回文鏈表
#include <bits/stdc++.h>
using namespace std;
struct Node
{int data;Node *next;
};
void createList(Node *&h,int n)
{Node *p,*r;h=new Node;h->next=NULL;r=h;for(int i=1; i<=n; i++){p=new Node;cin>>p->data;r->next=p;r=p;}r->next=NULL;
}
void printList(Node *h)
{Node *p;p=h->next;while(p){cout<<p->data<<" ";p=p->next;}cout<<endl;
}bool isPalindrome(Node *head)
{if (!head || !head->next){return true;}Node *slow = head;Node *fast = head;while (fast && fast->next){slow = slow->next;fast = fast->next->next;}Node *prev = NULL;Node *curr = slow;while (curr){Node *next = curr->next;curr->next = prev;prev = curr;curr = next;}Node *left = head->next;Node *right = prev;while (left && right){if (left->data != right->data){return false;}left = left->next;right = right->next;}return true;
}int main()
{int n;Node *h;cin>>n;createList(h,n);cout<<(isPalindrome(h)?"yes":"no");return 0;
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/164710.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/164710.shtml
英文地址,請注明出處:http://en.pswp.cn/news/164710.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MySql表中添加emoji表情

共五處需要修改。 語句執行修改&#xff1a; ALTER TABLE xxxxx CONVERT TO CHARACTER SET utf8mb4;

微型計算機原理MOOC題

一、8254 1.掉坑了&#xff0c;AL傳到端口不意味著一定傳到的是低位&#xff0c;要看控制字D5和D4&#xff0c;10是只寫高位&#xff0c;所以是0A00.。。 2. 3. 4.待解決&#xff1a;

優化C++資源利用:探索高效內存管理技巧

W...Y的主頁 &#x1f60a; 代碼倉庫分享&#x1f495; &#x1f354;前言&#xff1a; 我們之前在C語言中學習過動態內存開辟&#xff0c;使用malloc、calloc與realloc進行開辟&#xff0c;使用free進行堆上內存的釋放。進入C后對于動態內存開辟我們又有了新的內容new與dele…

CCC聯盟——UWB MAC(一)

本文在前面已經介紹了相關UWB的PHY之后&#xff0c;重點介紹數字鑰匙&#xff08;Digital Key&#xff09;中關于MAC層的相關實現規范。由于MAC層相應涉及內容比較多&#xff0c;本文首先從介紹UWB MAC的整體框架&#xff0c;后續陸續介紹相關的網絡、協議等內容。 1、UWB MAC架…

真心的表揚與鼓勵,勝過一萬句說教

今天我想和大家分享一下&#xff0c;怎樣跟孩子運用鼓勵和表揚。我記得魯道夫德雷克斯是阿德勒學派的心理學家&#xff0c;也是來自《孩子的挑戰》一書的作者&#xff0c;他說孩子們需要鼓勵&#xff0c;就像植物需要水&#xff0c;鼓勵能讓孩子知道自己做的事與自己是什么樣的…

非自定義Bean注解開發Bean配置類的注解開發

目錄 非自定義Bean注解開發 Bean配置類的注解開發 非自定義Bean注解開發 非自定義的Bean不能像自定義Bean使用Component進行管理&#xff0c;非自定義Bean要通過工廠的方式進行實例化&#xff0c;使用Bean標注方法即可&#xff0c;Bean的屬性文beanName 如果Bean工廠方法需要參…

[23] 4K4D: Real-Time 4D View Synthesis at 4K Resolution

paper | proj | code 提出一種基于K-Planes的4D point cloud Representation&#xff1b;提出一種Hybrid appearance model&#xff0c;包含image blending model和SH model。其中&#xff0c;image blending model將3D點映射回原圖中求得&#xff0c;SH model通過模型預測求得…

【工具欄】熱部署不生效

目錄 配置熱部署&#xff1a; 解決熱部署不生效&#xff1a; 首先檢查&#xff1a; 第一步&#xff1a; 第二步&#xff1a; 第三步&#xff1a; 第四步&#xff1a; 配置熱部署&#xff1a; https://blog.csdn.net/m0_67930426/article/details/133690559 解決熱部署不…

Python中的解析器argparse

import argparse## 構造解析器 argparse.ArgumentParser() parse argparse.ArgumentParser(description"caculateing the area of rectangle")## 添加參數 .add_argument() parse.add_argument("--length",typeint,default20,helpThe length of rectangle…

【追求卓越09】算法--散列表(哈希表)

引導 通過前面幾個章節的學習&#xff08;二分查找&#xff0c;跳表&#xff09;&#xff0c;我們發現想要快速查找某一個元素&#xff0c;首先需要將所有元素進行排序&#xff0c;再利用二分法思想進行查找&#xff0c;復雜度是O(logn)。有沒有更快的查找方式呢&#xff1f; 本…

微軟發布最新.NET 8長期支持版本,云計算、AI應用支持再強化

11 月 15 日開始的為期三天的 .NET Conf 在線活動的開幕日上&#xff0c;.NET 8作為微軟的開源跨平臺開發平臺正式發布。.NET 團隊著重強調云、性能、全棧 Blazor、AI 和 .NET MAUI 是.NET 8的主要亮點。.NET團隊在 .NET Conf 2023 [1]活動開幕式上表示&#xff1a;“通過這個版…

nginx 模塊相關配置及結構理解

文章目錄 模塊配置結構模塊配置指令先看一下 ngx_command_t 結構一個模塊配置的demo簡單模塊配置的案例演示 模塊上下文結構模塊的定義 模塊配置結構 Nginx中每個模塊都會提供一些指令&#xff0c;以便于用戶通過配置去控制該模塊的行為。 Nginx的配置信息分成了幾個作用域(sc…

使用注解的AOP編程

使用注解的AOP編程 當注解沒有參數時 當使用注解進行面向切面編程&#xff08;AOP&#xff09;時&#xff0c;你可以按照以下步驟來實現&#xff1a; 步驟&#xff1a; 1. 創建自定義注解&#xff1a; 首先&#xff0c;創建自定義的注解&#xff0c;以便在代碼中標記需要進…

Excel換不了行怎么解決?

方法一: 使用Alt Enter鍵 在Excel中&#xff0c;輸入文字時按下回車鍵&#xff0c;光標將會移到下一個單元格&#xff0c;如果想要換行&#xff0c;可以嘗試使用Alt Enter鍵。具體操作如下: 1.在單元格中輸入文字; 2.想要換行時&#xff0c;在需要換行的位置按下Alt Enter鍵; 3…

延時任務定時發布,基于 Redis 與 DB 實現

目錄 1、什么是延時任務&#xff0c;分別可以使用哪些技術實現&#xff1f; 1.2 使用 Redis 和 DB 相結合的思路圖以及分析 2、實現添加任務、刪除任務、拉取任務 3、實現未來數據的定時更新 4、將數據庫中的任務數據&#xff0c;同步到 Redis 中 1、什么是延時任務&#xff…

網絡運維與網絡安全 學習筆記2023.11.23

網絡運維與網絡安全 學習筆記 第二十四天 今日目標 VRRP負載均衡、BFD原理與配置、BFD典型應用 DHCP工作原理、全局模式DHCP VRRP負載均衡 VRRP單組缺陷 每網段存在一個VRRP組&#xff0c;缺點如下&#xff1a; 主網關數據轉發壓力大 備份網關不轉發任何數據 網絡設備利用…

Hook技術(鉤子技術)

HOOK&#xff08;鉤子技術&#xff09; 這里的hook我理解的意思就是通過攔截指令&#xff0c;將指令換成自己想要的指令&#xff0c;從而做道繞過原本的程序指令&#xff0c;要修改這個指令&#xff0c;要用匯編技術&#xff0c;從二進制入手。 擴展&#xff1a; 木馬病毒之…

git clone慢的解決辦法

在網站 https://www.ipaddress.com/ 分別搜索&#xff1a; github.global.ssl.fastly.net github.com 得到ip&#xff1a; 打開hosts文件 sudo vim /etc/hosts 在hosts文件末尾添加 140.82.114.3 github.com 151.101.1.194 github.global-ssl.fastly.net 151.101.65.194 g…

外部網關協議_邊界網關協議BGP

一.邊界網關協議BGP的基本概念 邊界網關協議(Border Gateway Protocol&#xff0c;BGP&#xff09;屬于外部網關協議EGP這個類別&#xff0c;用于自治系統AS之間的路由選擇協議。由于在不同AS內度量路由的“代價”(距離、帶寬、費用等&#xff09;可能不同&#xff0c;因此對于…

elasticsearch 7安裝

問題提前報 max virtual memory areas error max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] 如果您的環境是Linux&#xff0c;注意要做以下操作&#xff0c;否則es可能會啟動失敗 1 用編輯工具打開文件/etc/sysctl.conf 2 …