我搜索了很多,发现了很多类似的答案,但对我的确切问题没有任何帮助。
我正在为我的双链表做一个推送方法,而头部的指针工作正常,尾部的下一个和前一个指针不起作用请帮忙。
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");
}
}