顺序栈C语言实现:
#include <stdio.h>
#include <stdlib.h>
#define STACK_NINT_SIZE 10
#define ElemType int
#define Status int
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
Status InitStack(SqStack *S)
{
S->base=(ElemType *)malloc(STACK_NINT_SIZE*sizeof(ElemType));
if(!S->base)return 0;
S->top=S->base;
S->stacksize=STACK_NINT_SIZE;
return 1;
}
Status Push(SqStack *S,ElemType *e)
{
if(S->top-S->base==S->stacksize)return 0;
*S->top++=e;
return 1;
}
Status Pop(SqStack *S,ElemType *e)
{
if(S->top==S->base)return 0;
*e=*(S->top-1);
S->top--;
return 1;
}
ElemType GetTop(SqStack S)
{
if(S.top!=S.base)return *(S.top-1);
else printf("栈为空");
}
Status StackTraverse(SqStack S)
{
printf("栈中的元素为:");
while(S.top>S.base)
{
printf("%d ",*(--S.top));
}
printf("\n");
}
int main()
{
int op;
int flag=1;
SqStack S;
ElemType e;
printf("1.初始化栈\n");
printf("2.入栈\n");
printf("3.出栈\n");
printf("4.取栈顶元素\n");
printf("5.遍历栈\n");
printf("0.退出\n");
while(flag==1)
{
printf("请输入要进行的操作:");
scanf("%d",&op);
switch(op)
{
case 0:
{
flag=0;
break;
}
case 1:
{
InitStack(&S);
printf("初始化栈成功,栈的大小为%d\n",S.stacksize);
break;
}
case 2:
{
int temp;
scanf("%d",&temp);
Push(&S,temp);
break;
}
case 3:
{
int temp;
Pop(&S,&temp);
printf("元素%d出栈\n",temp);
break;
}
case 4:
{
printf("栈顶元素为:%d\n",GetTop(S));
break;
}
case 5:
{
StackTraverse(S);
break;
}
}
}
}
顺序栈Java实现
public class SqStack {
private Object[] data;
private int stacksize;
private int top;
public void InitStack(int initialSize){
if(initialSize>0){
this.data = new Object[initialSize];
this.stacksize = initialSize;
this.top = -1;
}else{
System.out.println("栈初始化失败!");
}
}
public boolean isEmpty(){
return top == -1 ? true : false;
}
public boolean isFull(){
return top == stacksize-1 ? true : false;
}
public void Push(Object value){
if(!isFull()){
System.out.println(value+"入栈");
this.data[++this.top] = value;
}else{
System.out.println("栈已满,无法进行入栈操作!");
}
}
public Object Pop(){
if(!isEmpty()){
Object value = this.data[this.top--];
return value;
}else{
return "栈为空,无法进行出栈操作!";
}
}
public Object GetTop(){
if(top>=0){
return this.data[top];
}else{
return "栈顶指针为空,无栈顶元素!";
}
}
public void StackTraverse(){
if(top>=0){
for(int i = top; i>=0; i-- ){
System.out.println(this.data[i]);
}
}else{
System.out.println("栈内元素为空!");
}
}
public static void main(String[] args) {
SqStack S = new SqStack();
S.InitStack(10);
S.Push(1);
S.Push(2);
S.Push(3);
S.Push(4);
S.StackTraverse();
}
}