数组结构实现堆栈较为简单,但因为如果堆栈本身是变动的话,数组大小并无法实现规划声明,因此,使用链表来实现堆栈可以随时改变链表的长度,不过缺点是设计算法较为复杂。
package Stack;
public class StackBylink {
public Node front;//指向堆栈底部的指针
public Node rear;//指向堆栈顶端的指针
public boolean isEmpty() {//类方法:判断堆栈是否为空堆栈
return front==null;
}
public void out_of_Stack() {//类方法:打印输出堆栈中的内容
Node current=front;//定义指向底部的指针
while(current!=null) {//输出堆栈中的内容
System.out.print("["+current.data+"]");
current=current.next;
}
System.out.println();
}
public void insert(int data) {//类方法:把指定的数据压入堆栈的顶端
Node newNode=new Node(data);//创建一个名为newNode的对象
if(this.isEmpty()) {//判断链表是否为空
front=newNode;
rear=newNode;
}else { //将数据压入堆栈
rear.next=newNode;
rear=newNode;
}
}
public void pop() {//类方法:从堆栈顶端弹出数据
Node newNode;//
if(this.isEmpty()) {
System.out.println("当前为空堆栈");
return;
}
newNode=front;
if(newNode==rear) {
front=null;
rear=null;
System.out.println("当前为空堆栈");
}else {
while(newNode.next!=rear)
newNode=newNode.next;
newNode.next=rear.next;
rear=newNode;
}
}
}
package Stack;
import java.io.*;
public class Linktest {
public static void main(String args[]) throws IOException{
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
StackBylink stack_by_linkedlist=new StackBylink();
int choice=0;
while(true) {
System.out.println("(0)结束(1)将数据压入堆栈(2)从堆栈弹出数据:");
choice=Integer.parseInt(buf.readLine());
if(choice==2) {
stack_by_linkedlist.pop();
System.out.println("数据弹出后堆栈的内容:");
stack_by_linkedlist.out_of_Stack();
}else if(choice==1) {
System.out.println("请输入要压入堆栈的数据:");
choice=Integer.parseInt(buf.readLine());
stack_by_linkedlist.insert(choice);
System.out.println("数据压入后堆栈中的内容:");
stack_by_linkedlist.out_of_Stack();
}else if(choice==0) {
break;
}else {
System.out.println("输入错误!");
}
}
}
}