1. 栈以顺序存储方式实现
(1)入栈:栈满 top==Maxsize-1
(2)出栈: 栈空top==-1;
#include<stdio.h>
#include<malloc.h>#include<iostream>
typedef struct stock
{
int Maxsize;
int top;
int *ps;
}Stock;
// 初始化栈
void InitStock(stock *s, int ms)
{
s->Maxsize = ms;
s->top = -1;
s->ps =(int*)malloc(ms*sizeof(int));
}
//出栈操作
int pop(stock*s)
{
if (s->top != -1)
{
return s->ps[s->top --];
}
}
// 入栈操作
void push(stock*s, int val)
{
if (s->top == s->Maxsize - 1)
{
printf("栈已满,%d不可入栈,正在处理,请稍等。",val);
getchar();
printf("%d已出栈,%d可入栈",pop(s), val);
getchar();
}
s->ps[++s->top] = val;
printf("%d已入栈", val);
getchar();
}
//释放栈空间
void freestock(stock*s)
{
s->Maxsize = 0;
free(s->ps);
s->ps = NULL;
}
void main()
{
Stock s; int i, ms;
int a[7] = { 10,11,12,13,14,15,16 };
printf("请输入栈的最大元素个数:\n");
std::cin>>ms;
InitStock(&s, ms);
for (i = 0; i < ms; i++)
{
push(&s,a[i] );
}
while (s.top != -1)
{
printf("%d已出栈\n", pop(&s));
getchar();
}
freestock(&s);
}
2. 栈以链式存储方式实现
#include<stdio.h>#include<malloc.h>
#define NULL 0
typedef struct student
{
int data;
struct student *next;
}node;
typedef struct queuestack
{
node *zhandi, *top;
}queue;
queue*push(queue *HQ, int x)
{
node*s;
s = (node*)malloc(sizeof(node));
s->data = x;
s->next = NULL;
if (HQ->zhandi == NULL)
{
HQ->zhandi = s;
HQ->top = s;
}
else
{
HQ->top->next = s;
HQ->top = s;
}
return HQ;
}
queue*pop(queue*HQ)
{
node*p; int x;
if (HQ->zhandi == NULL)
printf("\nyichu");
else
{
x = HQ->zhandi->data;
p = HQ->zhandi;
if (HQ->zhandi == HQ->top)
{
HQ->zhandi = NULL;
HQ->top = NULL;
}
else
{
while (p->next != HQ->top)
{
p = p->next;
}
HQ->top = p;
HQ->top->next = NULL;
}
}
return (HQ);
}