首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 鏈棧實現表達式求值:常見錯誤與修正指南

     編輯:程式設計疑難解答

使用 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.getline
  • 運算元轉換缺陷:僅支援單位數,多位數解析邏輯需完善

關鍵修正代碼片段

1. 修正棧彈出操作

error_code stack0::pop0(char& op) {
    if (empty()) return underflow;
    node *u = top;           // 直接指向棧頂
    top = top->next;         // 棧頂下移
    op = u->data0;           // 取出數據
    delete u;                // 釋放節點
    count--;
    return success;
}

2. 修正銷毀函數

void stack0::dest() {
    node *u = top;           // 無需 new node
    while (top) {
        u = top;
        top = top->next;
        delete u;
    }
}

3. 完善多位數解析

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 過程,養成嚴謹的記憶體管理習慣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved