java用链表实现栈
程序员文章站
2022-03-25 18:49:01
...
package cn.itcast.stack;
public class Stack01 {
public static void main(String[] args) {
ListNode listnode = new ListNode();
listnode.add(1);
listnode.add(2);
listnode.add(3);
listnode.add(4);
listnode.add(5);
int i = 6;
while(i>=0){
listnode.pop();
i--;
}
}
}
class ListNode{
Node head = new Node(0);
//Node temp = head;
public void add(int id){
Node node = new Node(id);
if(head.getNext()==null){
head.setNext(node);
}
else{
node.setNext(head.getNext());
head.setNext(node);
}
System.out.println("添加"+head.getNext().getId()+"成功");
}
public void pop(){
if(head.getNext()==null){
System.out.println("栈为空,出栈失败");
return;
}
else{
if(head.getNext().getNext()==null){
System.out.println("出栈结果为"+head.getNext().getId());
head.setNext(null);
return;
}
else{
System.out.println("出栈结果为"+head.getNext().getId());
head.setNext(head.getNext().getNext());
}
}
}
}
class Node {
private int id;
private Node next;
public Node(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}