前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《数据结构》 栈代码操作集合

《数据结构》 栈代码操作集合

作者头像
Steve Wang
发布2018-02-05 16:36:07
5360
发布2018-02-05 16:36:07
举报
文章被收录于专栏:从流域到海域从流域到海域

栈的基本操作代码,来自《数据结构-用C语言描述》(第二版)高教社 栈的数据结构相当于受限制(只能从栈顶取元素,先进后出LIFO)的顺序表或单链表,可以参考之前的博客。

代码语言:javascript
复制
/*以下为顺序栈*/
#define Stack_Size 50   /*设栈中元素为50*/
typedef struct {
    StackElemType elem[Stack_Size];
    int top;    //用来存放栈顶元素的下标
} SeqStack;
/*初始化*/
void InitStack(SeqStck) {
    S->top = -1;
}
/*进栈:将x置入新栈顶*/
int Push(SeqStack *S, StackElemType x) {
    if(S->top == Stack_Size -1) {
        return(FALSE);
    }
    S->top++;
    S->elem[S->top] = x;
    return(TRUE);
}
/*出栈*/
int Pop(SeqStack *S, StackElemType *x) {
    if(S->top = -1) {
        return(FALSE);
    }
    else {
        *x = S->elem[top];
        top--;      //修改栈顶指针 *x = S->elem[top--]
        return(TRUE);
    }
}
/*读栈顶*/
int GetTop(SeqStack *S, StackElemType *x) {
    if(top = -1) {
        return(FALSE);
    }
    else {
        *x = S->elem[S-top];
        return(TRUE);
    }
}
/*以下为链栈*/
typedef struct node {
    StackElemType data;
    struct node *next;
} LinkStackNode, *LinkStack;
/*初始化;即单链表的初始化*/
InitLink(LinkStack *top) {
    *top =(LinkStack)malloc(sizeof(Node));
    (*top)->next = NULL;
}
/*进栈*/
int Push(LinkStack top, StackElemType x) {
    LinkStackNode *temp;
    temp = (LinkStackNode *)malloc(sizeof(LinkStackNode));
    if(temp == NULL) {
        return(FALSE);
    }
    temp->data = x;
    temp->next = top->next;
    top->next = temp;
    return (TRUE);
}
int Pop(LinkStack top, StackElemType *x) {
    LinkStackNode *temp;
    temp = top->next;
    if(top == NULL){
        return (FALSE);
    }
    top->next = temp->next;
    *x = temp->data;
    free(temp);
    return(TRUE);
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年03月30日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档