class singlelinked{
private Node head = new Node(-1,-1);
public singlelinked(){}
public Node getHead(){return head;}//Determine if it is empty
public boolean isNull(){if(head.getNext()== null){return true;}else{return false;}}//Inserts data to the end of the list
public voidadd(Node node){if(head.getNext()== null){
head.setNext(node);return;}
Node temp = head;while(true){if(temp.getNext()== null){break;}
temp = temp.getNext();}
temp.setNext(node);return;}//Delete the data for the corresponding number
public intdel(){if(head.getNext()== null){
throw new RuntimeException("error");}
Node node = head;while(true){if(node.getNext().getNext()== null){break;}
node = node.getNext();}int value = node.getNext().getNum();
node.setNext(node.getNext().getNext());return value;}//Traversing the list
public voidlist(){if(head.getNext()== null){
System.out.println("error!");return;}
Node temp = head.getNext();while(true){
System.out.println(temp);if(temp.getNext()== null){break;}
temp = temp.getNext();}}}
class Node{
private int no;
private int num;
private Node next;
public voidsetNext(Node next){
this.next = next;}
public Node getNext(){return next;}
@Override
public String toString(){return"[num="+num+"]";}
public voidsetNo(int no){
this.no = no;}
public voidsetNum(int num){
this.num = num;}
public Node(int no,int num){
this.no = no;
this.num = num;}
public intgetNo(){return no;}
public intgetNum(){return num;}}
二、定义栈
class Arraystack{
private singlelinked singlelinked = new singlelinked();
private int top =-1;
public Arraystack(){}//Determines whether the stack is empty
public boolean isNull(){return singlelinked.isNull();}//push
public voidpush(int value){
top++;
Node node = new Node(top, value);
singlelinked.add(node);}//pop
public intpop(){int value = singlelinked.del();return value;}//Traversal stack
public voidlist(){ singlelinked.list();}}
2.测试代码
public staticvoidmain(String[] args){
Arraystack arraystack = new Arraystack();
arraystack.push(1);
arraystack.push(2);
arraystack.push(3);
arraystack.push(4);
arraystack.list();
System.out.println("-------------");
System.out.println(arraystack.pop());
System.out.println(arraystack.pop());
arraystack.list();}
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档文章目录JAVA单链表模拟栈一、定义节点和链表二、定义栈2.测试代码JAVA单链表模拟栈一、定义节点和链表class singlelinked{ private Node head = new Node(-1,-1); public singlelinked() { } public Node getHead() { return head; } //Determine