c语言数据结构-----栈的线性存储(源码奉上)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
奉上源代码


ststus.h


#ifndef STATUS_H
#define STATUS_H
#define    YES    1
#define    NO     0
typedef   int  Status;
typedef   int  SElemType;
#endif

stack.h


#ifndef  LISTH
#define  LISTH
#include  "status.h"
typedef  struct  Node
{
 SElemType  date;
 struct Node *next;
}LNode;
typedef   struct  
{
 LNode *top;
 int length;//记录栈的长度 
}SqStack;
/*
(1)初始化栈  InitStack(S)    
          (2)入栈  Push(S,item)      
          (3)出栈  Pop(S,item)          
          */
          void InitStack(SqStack *p);
          Status Push(SqStack *p,SElemType e);
          int  Count(SqStack *p);
          Status Pop(SqStack *p,SElemType *e);
          int  GetTopValue(SqStack *p);
#endif

stack.c


#include "stdio.h"
#include  "stack.h"
//初始化栈
void InitStack(SqStack *p)
   {
    p->length=0;
    p->top=NULL; 
   }
//进栈 (头插法)
Status Push(SqStack *p,SElemType e)
   {
    LNode *s;
    s = (LNode *)malloc(sizeof(LNode));
    if(s==NULL)
    return NO;
    s->date=e;
    s->next=p->top;
    p->top=s;
    p->length++; 
   } 
//栈内元素的个数
int  Count(SqStack *p)
   {
    return p->length;
   } 
//出栈 
Status Pop(SqStack *p,SElemType *e)
   {
    if(p->top==NULL)
    return NO;
    *e = p->top->date;
    p->top=p->top->next;
    free(p);
   } 
//取栈顶元素
int  GetTopValue(SqStack *p)
   {
    return p->top->date;
   } 

main.c


#include "stack.h"
#include <stdio.h>
int main()
{
  int i,t,n,value;
  SqStack sq;
  SqStack *L=&sq;
  LNode *g;



  printf("==================初始化栈表==================\n");
  InitStack(L);
  printf("初始化链表成功\n");



  printf("==================栈内添加元素(进栈)==================\n");//栈头进栈 
  printf("请输入你要进栈元素的个数:");
  scanf("%d",&n);
  printf("请依次输入%d个元素:",n);
  for(i=1;i<=n;i++)
  {
   scanf("%d",&value);
   Push(L,value);
  }
  g=L->top;
  printf("此时栈中的元素为:");
  for(i=0;i<n;i++)
  {
   printf("%d  ",g->date);
   g=g->next;
  }




  printf("\n==================获取栈内元素的个数==================\n");
  printf("此时栈内元素的个数为:%d\n",Count(L));




  printf("==================出栈==================\n");//栈头出栈 
  Pop(L,&value);
  printf("出栈的元素为:%d\n",value);
  printf("出栈后栈中的元素为:");
  g=L->top;
  for(;g!=NULL;g=g->next)
  printf("%d  ",g->date);



  printf("\n==================取栈顶元素==================\n");
  printf("栈顶元素为:%d",GetTopValue(L));
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱睡觉的小馨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值