Java链表模拟栈
1.定义一个节点
public class Node {
int no;
Node next;
public Node() {
}
public Node(int no) {
this.no = no;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}
2.定义一个链表
public class Linked {
private Node top=new Node();
int maxSize;
int[] stack;
public Linked(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public boolean isFull(){
return length(top)==maxSize;
}
public boolean isEmpty(){
return top.next==null;
}
public int length(Node node) {
if (node==null){
return 0;
}
Node temp =top;
int linkedLength =0;
while(temp.next != null){
linkedLength++;
temp = temp.next;
}
return linkedLength;
}
public void push(Node node){
if (isFull()){
System.out.printf("栈满,%d无法入栈",node.no);
return;
}
if(top.next== null){
top.next=node;
return;
}
Node temp = top.next;
if (node.no==temp.no){
System.out.printf("%d已经存在",node.no);
System.out.println("");
return;
}
top.next=node;
node.next=temp;
}
public void pop(){
if(isEmpty()){
System.out.println("栈空。。。");
return;
}
System.out.println("节点为:"+top.next.no);
top =top.next;
}
public void list(){
if(isEmpty()){
System.out.println("栈空。。。");
return;
}
Node temp = top;
while(temp.next != null){
System.out.println("节点为:"+temp.next.no);
temp = temp.next;
}
}
public void peek(){
if(isEmpty()){
System.out.println("栈空。。。");
return;
}
System.out.println("栈顶元素为:"+top.no);
}
}
3.写一个测试类
public class LinkedDemo {
public static void main(String[] args) {
Node p1 = new Node(3);
Node p2 = new Node(1);
Node p3 = new Node(5);
Node p4 = new Node(55);
Node p5 = new Node(566);
Linked stack = new Linked(4);
stack.push(p1);
stack.push(p2);
stack.push(p3);
stack.push(p4);
stack.push(p5);
System.out.println("-----");
stack.pop();
System.out.println("-----");
stack.list();
System.out.println("----");
stack.peek();
System.out.println("节点个数:"+stack.length(p1));
}
}
4.输出结果
栈满,566无法入栈-----
节点为:55
-----
节点为:5
节点为:1
节点为:3
----
栈顶元素为:55
节点个数:3