码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2021-02-06 11:59:33      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:turn   null   一个   class   sizeof   出栈   数据   ISE   fir   

栈的顺序存储

#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;
    }
}

 

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

标签:turn   null   一个   class   sizeof   出栈   数据   ISE   fir   

原文地址:https://www.cnblogs.com/Pio-GD/p/14379422.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!