【FROM:INTERNET 百科 && 維基百科】
進棧(PUSH)算法:
①若TOP≥n時,則給出溢出信息,作出錯處理(push前首先檢查棧是否已滿,滿則溢出;不滿則作②);
②置TOP=TOP+1(棧指針加1,指向進棧地址);
③S(TOP)=X,結束(X爲新進棧的元素);
退棧(POP)算法
①若TOP≤0,則給出下溢信息,作出錯處理(退棧前先檢查是否已爲空棧, 空則下溢;不空則作②);
②X=S(TOP),(退棧後的元素賦給X):
③TOP=TOP-1,結束(棧指針減1,指向棧頂)。
DEMO:FROM 百科
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 1024
/*define struct*/
typedef struct
{
int data[MAXSIZE];
int top;
}SeqStack;
/*init struct*/
SeqStack *Init_SeqStack()
{
SeqStack *s;
s=(SeqStack *)malloc(sizeof(SeqStack));
if (!s)
{
printf("空間不足\n");
return NULL;
}
else
{
s->top=-1;
return s;
}
}
/*if stack is empty */
int Empty_SeqStack(SeqStack *s)
{
if (s->top == -1)
{
return 1;
}
else
{
return 0;
}
}
/*push operator*/
int Push_SeqStack(SeqStack *s,int x)
{
if (s->top == MAXSIZE-1)
{
printf("Stack Full\n");
return 0;
}
else
{
s->top++;
s->data[s->top]=x;
return 1;
}
}
/*pop operator*/
int Pop_SeqStack(SeqStack *s,int *x)
{
if (Empty_SeqStack(s))
{
printf("Stack Empty \n");
return 0;
}
else
{
*x=s->data[s->top]; //top element into *x
s->top--;
return 1;
}
}
/*Get top element*/
int Top_SeqStack(SeqStack *s)
{
if (Empty_SeqStack(s))
{
printf("Stack Empty \n");
return 0;
}
else
{
return s->data[s->top];
}
}
/*print SeqStack*/
int Print_SeqStack(SeqStack *s)
{
int i;
printf("當前棧中的元素:\n");
for (i=s->top;i>=0;i--)
{
printf("%3d",s->data[i]);
}
printf("\n");
return 0;
}
int main(void)
{
SeqStack *L;
int n; //入棧元素個數
int element_value;
int m;
int i;
L=Init_SeqStack();
printf("STACK初始化完成\n");
printf("棧空:%d\n",Empty_SeqStack(L));
printf("請輸入入棧元素個數:\n");
scanf("%d",&n);
printf("請輸入要入棧的%d個元素:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&element_value);
Push_SeqStack(L,element_value);
}
Print_SeqStack(L);
printf("棧頂元素:%d\n",Top_SeqStack(L));
printf("\n============================================\n");
printf("請輸入要出棧的元素個數(不能超過%d個):\n",n);
scanf("%d",&n);
printf("依次出棧的%d個元素:\n",n);
for(i=0;i<n;i++)
{
Pop_SeqStack(L,&m);
printf("%3d",m);
}
printf("\n");
Print_SeqStack(L);
printf("棧頂元素:%d\n",Top_SeqStack(L));
getch();
return 0;
}
DEMO:push operator && pop operator
FROM:維基百科
typedef struct
{
size_t size;
int array[STACK_MAXSIZE];
}STACK;
void push(STACK *ps,int x)
{
if (ps->SIZE == STACK_MAXSIZE)
{
fputs("overflow\n",stderr);
abort();
}
else
{
ps->array[ps->size++]=x;
}
}
int pop(STACK *ps)
{
if (ps->size ==0)
{
fputs("underflow\n",stderr);
abort();
}
else
{
return ps->array[--ps->size] ;
}
}