栈是LIFO的,一般用数组来实现栈,当然也可以用链表实现。栈的最基本操作有出栈、入栈、判空、判满、取栈顶元素等。
保持一般性,栈顶元素指向栈最新插入的元素(注意和PC分开,PC指向下一个可用地址)。
1、栈的基本实现
public class Stack{
private int[] data;
private int top = -1;
private int max_length = 0;
public Stack(int max_length){
this.max_length = max_length;
data = new int[max_length];
}
boolean isFull(){
if(top == max_length-1){
return true;
}
else{
return false;
}
}
boolean isEmpty(){
if(top == -1){
return true;
}
else{
return false;
}
}
int getTop(){
if(isEmpty())
return -1;
else{
return data[top];
}
}
boolean pushStack(int datanum){
if(isFull()){
return false;
}
data[++top] = datanum;
return true;
}
int popStack(){
if(isEmpty()){
return -1;
}
else{
return data[top--];
}
}
public static void main(String[] args){
Stack stack = new Stack(3);
System.out.println(stack.isEmpty());
System.out.println(stack.isFull());
stack.pushStack(1);
stack.pushStack(2);
System.out.println(stack.isFull());
stack.pushStack(3);
System.out.println(stack.isFull());
System.out.println(stack.popStack());
System.out.println(stack.popStack());
System.out.println(stack.isEmpty());
System.out.println(stack.popStack());
System.out.println(stack.isEmpty());
}
}
c语言版:
#include <stdio.h>
#include<string.h>
#define STACK_LENGTH 10
typedef struct _Stack
{
int top;
int array[STACK_LENGTH];
}Stack;
int is_empty(Stack *p_stack)
{
if(p_stack->top == 0)
return 1;
else
return 0;
}
int get_size(Stack *p_stack)
{
return p_stack->top;
}
int is_full(Stack *p_stack)
{
if(p_stack->top == STACK_LENGTH)
return 1;
else
return 0;
}
int put_stack(Stack *p_stack,int a)
{
if(is_full(p_stack))
{
return 0;
}
else
{
p_stack->array[p_stack->top++] = a;
return 1;
}
}
int pop_stack(Stack *p_stack,int* n)
{
if(is_empty(p_stack))
{
return 0;
}
else
{
*n = p_stack->array[--(p_stack->top)];
return 1;
}
}
int get_top(Stack *p_stack)
{
if(is_empty(p_stack))
{
return -1;
}
else
{
return p_stack->array[p_stack->top-1];
}
}
int main(void)
{
Stack stack = {0,{0,}};
if(is_empty(&stack))
printf("stack is empty\n");
if(is_full(&stack))
printf("stack is full\n");
put_stack(&stack,5);
put_stack(&stack,3);
put_stack(&stack,1);
printf("size is :%d\n",get_size(&stack));
int temp = 0;
pop_stack(&stack,&temp);
pop_stack(&stack,&temp);
printf("top number is :%d\n",get_top(&stack));
return 0;
}