package 算法;
/**
* 双向链表实现 栈和队列
*/
public class test2 {
public static class Node<T> {
public T value;
public Node<T> last;
public Node<T> next;
public Node(T data) {
value = data;
}
}
//双向链表实现栈
public static class DoubleLinkedStack{
public test2.Node head = null;
public void pull(test2.Node value){
if(head==null){
//如果没有就直接装
head = value;
}else{
//如果有就把新的换成头
value.next = head;
head.last = value;
head = value;
}
}
public test2.Node pop( ){
if (head == null) {
return null;
}
test2.Node rt =head;
if(head.next!=null){
head.next.last=null;
head = head.next;
rt.next =null;
}else{
head =null;
}
return rt;
}
}
//双向链表实现队列 先进后出
public static class DoubleLinkedQueue{
public test2.Node head =null;
public test2.Node tail = null;
public void pull(test2.Node value){
if(head==null){
//如果没有就直接装
head = value;
tail = value;
}else{
//如果有就把新的换成头
head.last = value;
value.next = head;
head = value;
}
}
public test2.Node poll( ){
test2.Node rt = null;
if (tail != null) {
rt = tail;
if (tail.last != null) {
tail = tail.last;
rt.last = null;
tail.next = null;
}else {
tail=null;
head =null;
}
}
return rt;
}
}
public static void main(String[] args) {
//栈测试
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
DoubleLinkedStack doubleLinkedStack = new DoubleLinkedStack();
doubleLinkedStack.pull(n1);
doubleLinkedStack.pull(n2);
doubleLinkedStack.pull(n3);
doubleLinkedStack.pull(n4);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop());
doubleLinkedStack.pull(n1);
System.out.println(doubleLinkedStack.pop().value);
doubleLinkedStack.pull(n2);
doubleLinkedStack.pull(n3);
System.out.println(doubleLinkedStack.pop().value);
doubleLinkedStack.pull(n4);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop().value);
System.out.println(doubleLinkedStack.pop());
//队列测试
DoubleLinkedQueue doubleLinkedQueue = new DoubleLinkedQueue();
doubleLinkedQueue.pull(n1);
doubleLinkedQueue.pull(n2);
doubleLinkedQueue.pull(n3);
doubleLinkedQueue.pull(n4);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll());
doubleLinkedQueue.pull(n1);
System.out.println(doubleLinkedQueue.poll().value);
doubleLinkedQueue.pull(n2);
doubleLinkedQueue.pull(n3);
System.out.println(doubleLinkedQueue.poll().value);
doubleLinkedQueue.pull(n4);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll().value);
System.out.println(doubleLinkedQueue.poll());
}
}
双向链表实现 栈和队列
猜你喜欢
转载自blog.csdn.net/u010191034/article/details/120969546
今日推荐
周排行