自己学习所用,如有不对,欢迎指正
package www.hyh.stack;
import java.util.Scanner;
public class LinklistStackDemo {
public static void main(String[] args) {
LinklistStack stack=new LinklistStack(5);
String key = "";
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("show: 表示显示栈");
System.out.println("exit: 退出程序");
System.out.println("push: 表示添加数据到栈(入栈)");
System.out.println("pop: 表示从栈取出数据(出栈)");
System.out.println("请输入你的选择");
key = scanner.next();
switch (key) {
case "show":
stack.list();
break;
case "push":
System.out.println("请输入一个数");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int res = stack.pop();
System.out.printf("出栈的数据是 %d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
flag = false;
break;
default:
break;
}
}
System.out.println("程序退出~~~");
}
}
class Node{
private int value;
public Node next;
public Node(int value){
this.value=value;
}
public int getValue() {
return value;
}
}
class LinklistStack{
public int size;
private Node header=new Node(0);
public int elementCount;
public LinklistStack(){
size=0;
elementCount=0;
}
public LinklistStack(int size) {
elementCount=0;
this.size=size;
}
public boolean isEmpty(){
return elementCount==0;
}
public boolean isFull(){
return elementCount==size;
}
public void push(int value){
if(isFull()){
System.out.println("栈已满,无法入栈");
return;
}
Node n=new Node(value);
Node temp=header;
n.next=temp.next;
header.next=n;
elementCount++;
temp=n;
return;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈为空,无法出栈");
}
Node temp=header.next;
int value=temp.getValue();
header.next=temp.next;
elementCount--;
return value;
}
public void list(){
if(isEmpty()){
throw new RuntimeException("栈为空");
}
Node temp=header.next;
for(int i=1;i<=elementCount;i++){
System.out.printf("stack[%d]%d\n",elementCount+1-i,temp.getValue());
temp=temp.next;
}
}
}