用链式存储结构实现链栈(c语言)

代码:

//用链式存储结构实现链栈
#include<stdio.h>
#include<stdlib.h>
typedef int bool;
#define true 1
#define false 0

typedef struct StackNode{
  int data;              //数据域
  struct StackNode* next; //指针域
}StackNode,*StackNodeNode;

typedef struct LinkStack{
  StackNodeNode top; //栈顶指针
  int count; //栈顶元素个数
}LinkStack;

bool initLinkStack(LinkStack *S){
  if(S==NULL){
    return false;
  }
  S->top=NULL;
  S->count=0;
  return true;
}

bool clearLinkList(LinkStack *S){
  StackNode *temp;
  if(S->top==NULL||S->count==0){
    return false;
  }
  while(S->count){
    temp=S->top;
    S->top=temp->next;
    free(temp);
    S->count--;
  }
  return true;
}

bool push(LinkStack *S,int e){
  if(S==NULL){
    return false;
  }
  StackNode* temp=(StackNode*)malloc(sizeof(StackNode));
  temp->data=e;
  temp->next=S->top;
  S->top=temp;
  S->count++;
  return true;
}

bool pop(LinkStack *S,int* e){
  if(S==NULL){
    return false;
  }
  StackNode* temp=(StackNode*)malloc(sizeof(StackNode));
  *e=S->top->data;
  temp=S->top;
  S->top=temp->next;
  free(temp);
  S->count--;
  return true;
}

bool printStack(LinkStack S){
  if(S.top==NULL||S.count==0){
    return false;
  }
  StackNode* temp=S.top;
  while(temp){
    printf("%d ",temp->data);
    temp=temp->next;
  }
  printf("\n");
  return true;
}

int main(){
  LinkStack S;
  int e;
  initLinkStack(&S);
  for(int i=1;i<=5;i++){
    push(&S,i);
  }
  printStack(S);
  pop(&S,&e);
  printStack(S);
  clearLinkList(&S);
  return 0;
}

运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值