数组实现
public class ArrayStack {
public static void main(String[] args) {
Stack stack = new Stack(100);
stack.push(3);
stack.push(4);
stack.push(5);
stack.pop();
}
}
class Stack
{
public int MAX_NUM;
int[] arr;
int top;
public Stack(int MAX_NUM)
{
this.MAX_NUM = MAX_NUM;
arr = new int[this.MAX_NUM];
this.top = -1;
}
public void push(int num)
{
if (Full()) {
System.out.println("数组已满");
return;
}
top++;
arr[top] = num;
}
public boolean empty()
{
return this.top == -1 ? true : false;
}
public boolean Full()
{
if (this.top == (this.MAX_NUM - 1))
return true;
else
return false;
}
public void show_arr()
{
if (top == -1) {
System.out.println("队列为空");
return;
}
while (this.top != -1) {
System.out.println(arr[top]);
top--;
}
}
public void pop()
{
if (Full()) {
System.out.println("队列为空");
return;
}
System.out.println(arr[top]);
top--;
}
}
单链表实现栈功能代码
class Listnode{
int data;
Listnode next;
public Listnode(int data) {
this.data = data;
}
}
public class StackList {
private Listnode head_node;
int MAX_NUM;
public StackList() {
head_node =new Listnode(0);
this.MAX_NUM=5;
}
public void push(int num)
{
if(Full())
{
System.out.println("数组满了");
return;
}
Listnode temp=this.head_node;
Listnode new_node=new Listnode(num);
new_node.next=null;
new_node.next=head_node.next;
head_node.next=new_node;
this.MAX_NUM--;
}
public void pop()
{
if(empty())
{
System.out.println("栈为空");
return;
}
Listnode temp=this.head_node.next;
System.out.println(temp.data);
this.head_node.next=temp.next;
this.MAX_NUM++;
}
public boolean empty()
{
return this.head_node.next==null? true:false;
}
public boolean Full()
{
return this.MAX_NUM==0? true:false;
}
}