顺序栈
#include <stdio.h>
#include <stdlib.h>
#define MAX 8
//顺序栈
typedef struct
{
int data[MAX];
int top;
}SeqStack;
void intiStack(SeqStack &S){
S.top=-1;
}
bool IsFull(SeqStack &S)
{
return (S.top == MAX-1) ? true:false;
}
bool IsEmpty(SeqStack &S)
{
return (S.top == -1) ? true:false;
}
void Push(SeqStack &S, int e)
{
if( IsFull(S) )
{
printf("The stack is full, failed to push!\n");
return;
}
S.data[++S.top] = e;
}
int Pop(SeqStack &S)
{
int temp;
if( IsEmpty(S) )
{
printf("The stack is empty, failed to pop!\n");
return NULL;
}
temp= S.data[S.top--];
return temp;
}
void print(SeqStack &S)
{
int temp = S.top;
int i=0;
if(IsEmpty(S))
{
printf("The stack is empty!\n");
return;
}
printf("Print the stack:\n");
while( temp>=0 )
{
printf("%d ", S.data[i]);
i++;
temp--;
}
printf("\n");
}
void main()
{
SeqStack s;
intiStack(s);
Push(s,1);
Push(s,9);
Push(s,8);
Push(s,1);
Push(s,3);
Push(s,1);
Push(s,8);
print(s);
printf("Pop the top element: %d\n",Pop(s));
printf("Pop the top element: %d\n",Pop(s));
print(s);
}
链栈
#include <stdio.h>
#include <stdlib.h>
typedef struct StackNode
{
int data;
StackNode *next;
}StackNode;
typedef struct{
StackNode *top;
}LinkStack;
//建立一个头结点,头结点next域为null
void initStack(LinkStack &S){
S.top=(StackNode *)malloc(sizeof(StackNode));
S.top->next=NULL;
}
bool IsEmpty(LinkStack &S)
{
return S.top->next==NULL ? true:false;
}
void Push(LinkStack &S,int e)
{
StackNode *p=(StackNode *) malloc (sizeof(StackNode));
p->data = e;
p->next = S.top->next;
S.top->next = p;
}
int Pop(LinkStack &S)
{
StackNode *p;
int temp;
if(IsEmpty(S))
{
printf("The stack is empty, failed to pop!\n");
return NULL;
}
p=S.top->next;
temp=p->data;
S.top->next=S.top->next->next;
free(p);
return temp;
}
void print(LinkStack &S)
{
StackNode *p;
p=S.top->next;
if(IsEmpty(S))
{
printf("The stack is empty!\n");
return;
}
printf("Print the stack (from right to left):\n");
while(p)
{
printf("%d ", p->data);
p=p->next;
}
printf("\n");
}
void main()
{
LinkStack s;
initStack(s);
Push(s,1);
Push(s,9);
Push(s,8);
Push(s,3);
Push(s,5);
print(s);
printf("Pop the top element: %d\n",Pop(s));
print(s);
}