使用 C++ 實現基於鏈棧的中綴表達式求值是經典數據結構練習。但初學者常因指針操作不當、頭文件缺失、棧操作邏輯錯誤導致程式崩潰。本文針對典型錯誤提供完整修正方案。
#include 後為空,應包含 iostream、cstdio、cstdlib 等pop0/pop1 中 top->next = u->next; 應為 top = u->next;dest() 中 node *u = new node; 多餘,直接用 node *u = top;gets(str) 不安全,建議用 fgets 或 cin.getlineerror_code stack0::pop0(char& op) {
if (empty()) return underflow;
node *u = top; // 直接指向棧頂
top = top->next; // 棧頂下移
op = u->data0; // 取出數據
delete u; // 釋放節點
count--;
return success;
}
void stack0::dest() {
node *u = top; // 無需 new node
while (top) {
u = top;
top = top->next;
delete u;
}
}
if (!ifopt(str[i])) {
double num = 0;
while (i < strlen(str) && !ifopt(str[i])) {
if (isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
}
i++;
}
object.push1(num);
}
確保包含完整頭文件:
#include
#include
#include
#include
#include
using namespace std;
掌握鏈棧操作的指針邏輯是關鍵,建議配合圖解逐步追蹤 push/pop 過程,養成嚴謹的記憶體管理習慣。