首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

順序棧 C 語言完整實現

     編輯:C++ 入門

結構定義

#define MAXSIZE 1000
typedef int ElemType;
typedef struct {
    ElemType data[MAXSIZE];
    int top;  // -1 為空
} SqStack;

核心操作

void InitStack(SqStack *&s) { s = (SqStack*)malloc(sizeof(SqStack)); s->top = -1; }
void DestroyStack(SqStack *&s) { free(s); s = NULL; }
int StackEmpty(SqStack *s) { return s->top == -1; }
int StackLength(SqStack *s) { return s->top + 1; }
int Push(SqStack *&s, ElemType e) {
    if (s->top + 1 == MAXSIZE) return 0;
    s->data[++s->top] = e; return 1;
}
int Pop(SqStack *&s, ElemType &e) {
    if (s->top == -1) return 0;
    e = s->data[s->top--]; return 1;
}
int GetTop(SqStack *s, ElemType &e) {
    if (s->top == -1) return 0;
    e = s->data[s->top]; return 1;
}
void DispStack(SqStack *s) {
    for (int i=s->top; i>=0; --i) printf("%d ", s->data[i]);
    puts("");
}

測試主函數

int main() {
    SqStack *s = NULL; InitStack(s);
    int a[] = {3,76,4,25,7,8,2,43,212};
    for (int x : a) { Push(s,x); DispStack(s); }
    ElemType e; GetTop(s,e); printf("Top=%d Len=%d\n", e, StackLength(s));
    while (!StackEmpty(s)) { Pop(s,e); DispStack(s); }
    DestroyStack(s);
    return 0;
}

要點

  • top 初始 -1,指向棧頂元素。
  • 指針傳引用 SqStack *&s 以便修改指針本身(如初始化、銷毀)。
  • 返回 int 表示成功/失敗,避免異常。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved