顺序栈
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
//顺序栈
#define MAXSIZE 5 //宏定义后不加;
typedef struct
{ //数据类型
int elem[MAXSIZE];
int top;
int stackSize;
} Sqstack;
/*S.elem[S.top]是栈顶元素
* S.top=-1 栈空
* S.top+1是栈中存放的元素的个数
* S.top+1=S.stackSize是栈满条件
*/
void InitSqstack(Sqstack* S)
{
S->top = -1;
S->stackSize = MAXSIZE;
}
int Push(Sqstack* S, int e)
{ //栈满
if (S->top + 1 >= S->stackSize) return 0;
//将e插入栈顶
else {
//S1 S->top+1 S2 把新的top的elem[S->top]赋为e
S->elem[++S->top] = e; return 1;
}
}
int Pop(Sqstack* S, int* e)
{
//栈空
//用->
if (S->top == -1) return 0;
//S1 把elem[S->top]赋给e S2 S->top-1
*e = S->elem[S->top--]; return 1;
}
int GetTop(Sqstack S, int* e)
{ //用.
if (S.top == -1) return 0;
*e = S.elem[S.top]; return 1;
}
int StackTraverse(Sqstack S)
{
if (S.top == -1) return 0;
for (int i = S.top; i > -1; i--)
{
printf("%d ",S.elem[i]);
}
printf("\n");
}
int main() {
Sqstack s;
int e = 0;
InitSqstack(&s);
Push(&s, 1);
Push(&s, 2);
Push(&s, 3);
Push(&s, 4);
Pop(&s, &e);
printf("e=%d\n", e);
Push(&s, 5);
StackTraverse(s);
Push(&s, 6);
StackTraverse(s);
GetTop(s, &e);
printf("e=%d\n", e);
StackTraverse(s);
}
链栈
不带头指针的链表实现,因为栈操作的元素位置固定(都在栈顶)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
//链栈
typedef struct linkstack {
int data;
struct linkstack* next;
}SNode,*Linkstack;
int initLinkstack(Linkstack* s) {
*s = NULL; return 0;
}
//传参:栈顶指针s的指针类型(指针的指针)
int Push(Linkstack* s, int e) {
//malloc在stdlib.h中
//S1申请新结点
Linkstack p = (Linkstack) malloc(sizeof(SNode));
/*
//new 语法 char * p=new char("Hello");
Linkstack p = new SNode;
*/
if (!p) return 0;
//s2新栈顶记住原栈顶
p->data = e; p->next = *s;
//头指针改完新结点
*s = p;
return 1;
}
int Pop(Linkstack* s, int* e) {
//判断栈空
if (!s) { printf("栈空\n"); return 0; }
//p记录原栈顶指针
Linkstack p = *s; *e = p->data;
//s改为新栈顶
*s = p->next;
//删除原栈顶
free(p);
return 1;
}
int GetTop(Linkstack s, int *e){
if (!s) { printf("栈空\n"); return 0; }
*e = s->data; return 1;
}
void disp(Linkstack s) {
if (!s) return;
Linkstack p = s;
while (p)
{
printf("%d ", p->data); p = p->next;
}
printf("\n");
}
int main() {
Linkstack s;
int e = 0;
initLinkstack(&s);
Push(&s, 1);
Push(&s, 2);
Push(&s, 3);
Push(&s, 4);
Pop(&s, &e);
printf("e=%d\n", e);
Push(&s, 5);
disp(s);
Push(&s, 6);
disp(s);
GetTop(s, &e);
printf("e=%d\n", e);
disp(s);
}
链栈没有大小限制。