顺序栈
#include<stdlib.h>
#include <iostream>
#include<string>
#include<iomanip>
using namespace std;
typedef int datatype;
#define maxsize 64
typedef struct
{
datatype data[maxsize];
int top;
}seqstack;
void setnull(seqstack *s)
{
s->top = -1;
}
int empty(seqstack *s)
{
if (s->top == -1)return 1;
else return 0;
}
void displayStack(seqstack *s)
{
int i=0;
while(i<=s->top)
{
cout<<s->data[i];
++i;
}
cout<<endl;
}
void pushStack(seqstack *s,datatype x)
{
if (s->top >= maxsize - 1) { printf("overflow.\n"); }
else { s->top++;s->data[s->top] = x; }
}
datatype popStack(seqstack *s)
{
if (s->top < 0) { printf("underflow.\n"); }
else
{
return s->data[s->top--];
}
}
int main()
{
seqstack s;
setnull(&s);
for (int i = 0;i < 30;i++)pushStack(&s,i);
displayStack(&s);
for (int i = 0;i < 30;i++){popStack(&s);displayStack(&s);}
return 0;
}
#include<stdio.h>
typedef int datatype;
#define maxsize 64
typedef struct
{
datatype data[maxsize];
int top;
}seqstack;
void setnull(seqstack *s)
{
s->top = -1;
}
int empty(seqstack *s)
{
if (s->top == -1)return 1;
else return 0;
}
void push(seqstack *s,datatype x)
{
if (s->top >= maxsize - 1) { printf("overflow.\n"); }
else { s->top++;s->data[s->top] = x; }
}
void pop(seqstack *s)
{
if (s->top < 0) { printf("underflow.\n"); }
else { s->top--; }
}
datatype top(seqstack *s)
{
return s->data[s->top];
}
void print(seqstack *s)
{
for (int i = 0;i <= s->top;i++)
{
printf("%4d", s->data[i]);
if ((i+1) % 10 == 0)putchar(10);
}
putchar(10);
}
void main()
{
seqstack s;
setnull(&s);
for (int i = 0;i < 30;i++)
{
push(&s,i);
pop(&s);
}
print(&s);
}
链栈
#include<stdlib.h>
#include <iostream>
#include<string>
#include<iomanip>
using namespace std;
typedef char datatype;
#define maxsize 64
typedef struct node
{
datatype data;
struct node* next;
}linkstack;
void displayStack(linkstack *s)
{
while(s!=NULL)
{
cout<<s->data;
s=s->next;
}
}
linkstack* createStack()
{
linkstack *s,*top;
top=NULL;
datatype ch;
ch=cin.get();
while(ch!='\n')
{
s=(linkstack *)malloc(sizeof(linkstack));
s->data=ch;
s->next=top;
top=s;
ch=cin.get();
}
return top;
}
linkstack* pushStack(linkstack *top,datatype data)
{
linkstack *s=(linkstack *)malloc(sizeof(linkstack));
s->data=data;
s->next=top;
top=s;
return top;
}
datatype popStack(linkstack *top)
{
datatype data;
data=top->data;
linkstack *temp=top;
top=top->next;
free(temp);
return data;
}
int main()
{
linkstack *top;
top=createStack();
top=pushStack(top,'s');
popStack(top);
displayStack(top);
return 0;
}