C语言实现堆栈(栈)的数据结构

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define elemtype int
struct Node{
 elemtype data;
 struct Node *next;
};

struct stack{
 struct Node *top;//栈顶指针
};

elemtype getTop(struct stack *s)
{//返回栈顶指针元素
 if(s->top==NULL)
 printf("The stack is empty/n");
 return s->top->data;
}

struct stack * createstack()
{/*创建一个堆栈*/
 struct stack *s;
 s=(struct stack *)malloc(sizeof(struct stack));
 s->top=NULL;
 return s;
}

struct stack * push(struct stack *s,elemtype e)
{//向栈顶插入一个结点
 struct Node *newptr;//指向新结点的指针
 newptr=malloc(sizeof(struct Node));
 assert(newptr!=NULL);
 newptr->data=e;
 newptr->next=NULL;
 newptr->next=s->top;
 s->top=newptr;
 return s;
}

struct stack * pop(struct stack *s,elemtype *e)
{//删除栈顶元素,并将值存入e中
 struct Node *temp=s->top;
 *e=s->top->data;
 s->top=s->top->next;
 free(temp);
 return s;
}

int empty(struct stack *s)
{
 return s->top==NULL;
}

void printstack(struct stack *s)
{
 if(s->top==NULL)
 printf("the queue is empty./n");
 else
 {
  struct Node *p;
  p=s->top;
  printf("the stack is:/n");
  while(p!=NULL)
  {
   printf("%d-->",p->data);
   p=p->next;
  }
 }
}

int main()
{
 struct stack *s;
 int e;
 s=createstack();
 s=push(s,1);
 s=push(s,2);
 s=push(s,3);
 s=push(s,4);
 printstack(s);
 s=pop(s,&e);
 printstack(s);
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值