[英]Java Double Linked List Stack Tail error
我搜索了很多类似的答案,但没有什么可以解决我的确切问题。
我正在为我的双向链接列表执行push方法,而头部的指针工作正常,尾部的下一个和上一个指针不起作用,请帮忙。
public class MyStack<E> implements MyDeque {
private Node<E> head;
private Node<E> tail;
private int size;
public MyStack() {
head = null;
tail = null;
size = 0;
}
public void push(Object element) {
Node<E> newNode = new Node(element);
if(size == 0) {
Node temp = new Node(head);
head = newNode;
head.next = head;
head.previous = head;
tail = head;
tail.next = head;
tail.previous = temp;
}
else {
newNode.previous = head;
head = newNode;
newNode.next = tail;
(tail.next).previous = tail;
}//else statement
size++;
}//push()
public Object peek() {
if (size==0) return null;
else
return head;
}
public Object pop() {
size--;
if(size == 0)
return null;
else {
Node temp = new Node(head.previous);
head = head.previous;
head.next = tail;
head.previous = temp;
return head;
}//else
}//pop()
@Override
public int size() {
return size;
}
private class Node<E> {
private E data;
private Node<E> next;
private Node<E> previous;
public Node(E data) {
this.data = data;
this.next = null;
this.previous = null;
}
public Node(E data, Node<E> next, Node<E> previous) {
this.data = data;
this.next = next;
this.previous = previous;
}//constructor
public String toString() {
return data+"";
}
}//class Node<E>
public String toString() {
return (head+" Head\n" + head.next +" Head.Next\n" + head.previous+ " Head.previous\n"
+ tail+" Tail\n" + tail.next+" tail.next\n" + tail.previous+" tail.previous\n");
}
}
在堆栈为空时推送对象的情况看起来不正确。 添加的第一个节点应分配给head。 然后,尾部成为新节点的头,该新节点成为尾部节点的尾部,新节点本身成为尾部。
通常在堆栈中,您在末尾(尾部)添加和删除元素。 该代码并不太清楚您要对头成员和尾成员执行的操作。 如果将它们命名为firstNode和lastNode,那么对您来说可能会更清晰。
我实际上可以看到此代码的一些问题
public class MyStack<E> implements MyDeque {
private Node<E> head;
private Node<E> tail;
private int size;
public MyStack() {
head = null;
tail = null;
size = 0;
}
看起来不错
public void push(Object element) {
Node<E> newNode = new Node(element);
if(size == 0) {
Node temp = new Node(head);
head = newNode;
head.next = head;
head.previous = head;
tail = head;
tail.next = head;
tail.previous = temp;
}
else {
newNode.previous = head;
head = newNode;
newNode.next = tail;
(tail.next).previous = tail;
}//else statement
size++;
}//push()
有点困惑为什么要使用对象而不是通用E。
您真的不需要这里的temp值,实际上,当您设置tail.previous = temp
时,看起来好像在打破以前的值。
在其他情况下,您未正确设置tail.previous。 最后一行应为tail.previous = head
。 您也错过了头。
所以收拾了一下
public void push(E element) {
Node newNode = new Node(E);
if(size == 0) {
head = newNode;
head.next = head;
head.previous = head;
tail = head;
} else {
newNode.previous = head;
head.next = newNode;
newNode.next = tail;
tail.previous = newNode;
head = newNode;
}
size++;
}
在您的pop方法中,您可能希望在进行大小检查后移动大小减小量,否则,弹出时1元素堆栈将返回null。
编辑:使用单链列表或至少不是圆形双链列表可能会更容易。
并且在末尾添加可能是更常规的处理方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.