思路:
1.创建一个节点,节点包含编号,next和pre;
2.根据创建的节点创建双向链表
注意:写遍历栈函数时要创建临时节点来遍历,不然就不是遍历栈,而是出栈了,容易造成空指针异常。
//用双向链表创建栈
class LinkedListStack{
//创建头节点
private Node head = new Node(-1);
//创建top节点指向最后一个节点
private Node top = head;
public Node getHead(){
return head;
}
public Node getTop(){
return top;
}
//栈空
public boolean isEmpty(){
if( head.next == null ){
System.out.println("栈为空!");
return true;
}
return false;
}
//入栈
public void push( Node node ){
node.next = top.next;
top.next = node;
node.pre = top;
top = top.next;
}
//出栈
public void pop(){
if(top == head){
System.out.println("栈空,无法出栈!");
return;
}
System.out.println(top);
top = top.pre;
}
//遍历出栈
public void list(){
// //判断链表是否为空
// if(head.next == null){
// System.out.println("链表为空");
// return;
// }
//
// Node temp = top;
// while(temp != head ){
//
// System.out.println(temp);
// temp = temp.pre;
// }
Node temp = top;
if(temp == head){
System.out.println("链表已空!");
return;
}
while(temp != head){
System.out.println(temp);
temp = temp.pre;
}
}
}
执行如下操作:
执行结果如图:
完整代码如下:
package DataStructures.stack;
public class LinkedListStackDemo {
public static void main(String[] args) {
LinkedListStack linkedListStack = new LinkedListStack();
Node node1 = new Node(23);
Node node2 = new Node(24);
Node node3 = new Node(25);
Node node4 = new Node(26);
Node node5 = new Node(27);
//入栈
linkedListStack.push(node1);
linkedListStack.push(node2);
linkedListStack.push(node3);
linkedListStack.push(node4);
linkedListStack.push(node5);
System.out.println("此时栈中的数据为:");
linkedListStack.list();
System.out.println("执行6次出栈:");
linkedListStack.pop();
linkedListStack.pop();
linkedListStack.pop();
linkedListStack.pop();
linkedListStack.pop();
linkedListStack.pop();
System.out.println("此时栈中的数据为:");
linkedListStack.list();
}
}
//创建节点
class Node{
public int no;
public Node next;
public Node pre;
public Node( int no ){
this.no = no;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
'}';
}
}
//用双向链表创建栈
class LinkedListStack{
//创建头节点
private Node head = new Node(-1);
//创建top节点指向最后一个节点
private Node top = head;
public Node getHead(){
return head;
}
public Node getTop(){
return top;
}
//栈空
public boolean isEmpty(){
if( head.next == null ){
System.out.println("栈为空!");
return true;
}
return false;
}
//入栈
public void push( Node node ){
node.next = top.next;
top.next = node;
node.pre = top;
top = top.next;
}
//出栈
public void pop(){
if(top == head){
System.out.println("栈空,无法出栈!");
return;
}
System.out.println(top);
top = top.pre;
}
//遍历出栈
public void list(){
// //判断链表是否为空
// if(head.next == null){
// System.out.println("链表为空");
// return;
// }
//
// Node temp = top;
// while(temp != head ){
//
// System.out.println(temp);
// temp = temp.pre;
// }
Node temp = top;
if(temp == head){
System.out.println("链表已空!");
return;
}
while(temp != head){
System.out.println(temp);
temp = temp.pre;
}
}
}