C语言实现栈

112 阅读1分钟

 

1.栈的顺序存储实现

(1)栈的定义

#define Maxsize 10
typedef int ElemType;
typedef struct {
    ElemType data[Maxsize];
    int top;
}SqStack;

(2)初始化

void InitStack(SqStack& S) {
    S.top = -1;
}

(3)判断栈空

bool StackEmpty(SqStack& S) {
    if (S.top == -1)
        return true;
    else
        return false;
}

(4)进栈操作

bool Push(SqStack& S, ElemType e) {
    if (S.top == Maxsize - 1)
        return false;
    S.data[++S.top] = e;
}

(5)出栈操作

bool Pop(SqStack& S, ElemType x) {
    if (S.top == -1)
        return false;  //栈空,报错
    x = S.data[S.top--];
    return true;
}

(6)读栈顶元素

bool GetTop(SqStack& S, ElemType &x) {
    if (S.top == -1)
        return false;  //栈空,报错
    x = S.data[S.top];
    return true;
}

2.栈的链式存储实现(等同于头插法建立单链表)

(1)栈的定义

typedef int ElemType;
typedef struct Linknode {
    ElemType data;
    Linknode* next;
}Linknode, *LiStack;

(2)初始化

bool InitStack(LiStack& S) {
    S = (LiStack)malloc(sizeof(Linknode));
    if (S == NULL)
        return false;
    S->next = NULL;
    return true;
}

(3)判断栈空

bool IsEmpty(LiStack& S) {
    if (S == NULL) {
        printf("无效指针");
        return true;
    }
    if (S->next == NULL)
        return true;
    else
        return false;
}

(4)进栈操作

bool Push(LiStack& S,ElemType x) {
    LiStack s = (Linknode*)malloc(sizeof(struct Linknode));
    s->data = x;
    s->next = S->next;
    S->next = s;
}

(5)出栈操作

bool Pop(LiStack& S) {
    if (IsEmpty(S))
        return false;
    Linknode* p = (Linknode*)malloc(sizeof(struct Linknode));
    p = S->next;
    S->next = p->next;
    free(p);
    return true;
}

(6)读栈顶元素

bool Top(LiStack& S, ElemType& x) {
    if (IsEmpty(S))
        return false;
    x = S->next->data;
    return true;
}