1. 顺序栈
#include<stdio.h>
//进栈,进栈元素为elem,top值为栈顶 ,a为数组
int push(int *a,int top,int elem){
a[++top]=elem;
return top;
}
//出栈
int pop(int *a,int top){
if(top==-1)
{
printf("空栈!!!\n");
return -1;
}
printf("出栈元素为:%d\n",a[top]);
top--;
return top;
}
main(){
int a[100];
int top=-1;
pop(a,top);
top=push(a,top,1);
top=push(a,top,100);
top=push(a,top,999);
top=pop(a,top);
top=pop(a,top);
top=pop(a,top);
}
2.链栈
#include<stdio.h>
#include<stdlib.h>
typedef struct lineStack{
int data;
struct lineStack *next;
}lineStack;
//进栈操作
lineStack* push(lineStack *stack,int elem){
//创建存储新元素的结点
lineStack *line=(lineStack*)malloc(sizeof(lineStack));
//将进栈元素赋值给新结点line
line->data=elem;
//新结点与头结点建立逻辑关系,新结点指向头结点
line->next=stack;
//跟新栈顶位置
stack=line;
//返回栈顶位置
return stack;
}
//入栈操作
lineStack* pop(lineStack *stack){
//判断原栈是否为空
if(stack){
//声明一个新指针指向头结点(栈顶结点)
lineStack *p=stack;
//跟新栈顶结点
stack=stack->next;
printf("出栈的元素为:%d\n",p->data);
//判断新栈是否为空
if(stack){
printf("栈顶元素为:%d\n",stack->data);
}else
{
printf("栈已空!!!\n");
}
//释放空间
free(p);
} else
{
printf("栈内没有元素!!!\n");
return stack;
}
return stack;
}
main()
{
//创建一个空结点
lineStack *stack=NULL;
//将元素1进栈
stack=push(stack,1);
//将元素520进栈
stack=push(stack,520);
//将元素999进栈
stack=push(stack,999);
//出栈(先进后出)
stack=pop(stack);
stack=pop(stack);
stack=pop(stack);
stack=pop(stack);
}
还没有评论,来说两句吧...