数据结构:2.6 栈的顺序存储和链式存储

时间:2021-02-06 11:59:33   收藏:0   阅读:0

栈的顺序存储

#define MaxSize 1000
typedef struct SNode *Stack;
struct SNode {
    ElementType Data[MaxSize];
    int Top;
};

//入栈
void Push( Stack PtrS, ElementType item ) {
    if ( PtrS->Top == MaxSize-1 ) {
        printf("堆栈满"); return;
    }
    else {
        PtrS->Data[++(PtrS->Top)] = item;
        return;
    }
}

//出栈
ElementType Pop( Stack PtrS ) {
    if ( PtrS->Top == -1 ) {
        printf("堆栈空");
        return ERROR; // 标志错误
    }
    else {
        return (PtrS->Data[(PtrS->Top)--]);
    }
}

栈的链式存储

typedef struct SNode *Stack;
struct SNode {
    ElementType Data;
    struct SNode *Next;
};

//构建一个堆栈头结点,返回指针,该指针的Next指向栈顶
Stack CreatStack() {
    Stack S;
    S = (Stack)malloc(sizeof(struct SNode));
    S->Next = NULL;
    return S;
}

//判断空不空
int IsEmpty ( Stack S ) {
    return ( S->Next == NULL );
}

//入栈
void Push ( ElementType item, Stack S ) {
    struct SNode *TmpCell;
    TmpCell = (struct SNode *)malloc(sizeof(struct SNode));
    TmpCell->Data = item;
    TmpCell->Next = S->Next;
    S->Next = TmpCell;
}

//出栈
ElementType Pop ( Stack S ) {
    struct SNode *FirstCell;
    ElementType TopElem;
    if ( IsEmpty(S) ) {
        printf("堆栈空"); return NULL;
    } 
    else {
        FirstCell = S->Next;
        S->Next = FirstCell->Next;
        TopElem = FirstCell->Data;
        free(FirstCell);
        return TopElem;
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!