奉上源代码
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));
}
版权声明:本文为qq_45696288原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。