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

栈的基本操作代码,来自《数据结构-用C语言描述》(第二版)高教社

栈的数据结构相当于受限制(只能从栈顶取元素,先进后出LIFO)的顺序表或单链表,可以参考之前的博客。

/*以下为顺序栈*/
#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);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值