引入
在数据结构--数组实现栈和队列-CSDN博客这篇文章中我们已经用数组实现了栈和队列,那么我们再练习一下链表实现吧!o(* ̄▽ ̄*)ブ
既然是链表,那么前提给出一个创建节点的封装类:
java
public class Node {
int data;
Node next;
public Node(){
//空构造函数
}
public Node(int data){
this.data=data;
this.next=null;
}
@Override
public String toString() {
return (this.next == null) ? this.data + " " : this.data + " " + this.next.toString();
}
}
1.用链表实现入栈和出栈
java
public class ListStack {
private Node top;
//入栈(链表)
public void put(int value){
Node newNode=new Node(value);
newNode.next=top;
top=newNode;
System.out.println("入栈成功!");
}
//出栈
public void get(){
if(top==null){
System.out.println("栈已经空了!");
return;
}
System.out.println(top.data);
top=top.next;
}
}
一个测试Main:
java
public class Test {
public static void main(String[] args) {
ListStack stack=new ListStack();
stack.put(4);
stack.put(3);
stack.put(6);
stack.put(1);
stack.get();
stack.get();
stack.get();
stack.get();
stack.get();
}
}
得到结果:
2.用链表实现入队和出队
java
public class ListQueue {
private Node left;
private Node right;
public void put(int value){
Node newNode=new Node(value);
if(left==null&&right==null){
left=newNode;
right=newNode;
System.out.println("入队成功");
return;
}
left.next=newNode;
left=newNode;
System.out.println("入队成功");
}
public void get(){
if(right==null){
System.out.println("队列已空!");
return;
}
System.out.println(right.data);
right=right.next;
}
}
得到结果: