我正在尝试创建双链表,但我遇到了removeLast方法的问题。
public class Node<E> {
E data;
public Node<E> next;
public Node<E> prev;
public Node(E d)
{
data = d;
}
public E getData()
{
return data;
}
}
public class TestList<E> {
Node<E> head;
Node<E> tail;
public void addLast(E data)
{
Node<E> newData = new Node<E>(data);
if (head == null)
{
head = newData;
tail = newData;
}
else
{
Node<E> current = head;
while (current.next != null)
current = current.next;
current.next = newData;
tail = current.next;
}
}
public void removeLast()
{
if (head == null)
System.out.println("List is empty!");
else
{
Node<E> current = tail;
}
}
例如,如果我有一个整数列表,其中值为1,3,5,其中1为头部,5为尾部,在我的removeLast方法中,我想知道如何将current.prev指向3而current.prev.prev现在指向1,它只会指向下一个值,在这种情况下为null。
答案 0 :(得分:0)
你可以这样做:
tail.prev.next
指向null
,然后点tail = prev
像这样:
public void removeLast() {
if (head == null) {
System.out.println("List is empty!");
return;
}
if (head == tail) {
head = tail = null;
return;
}
Node<E> prev = tail.prev;
prev.next = null;
tail = prev;
}
答案 1 :(得分:0)
您必须在两种方法中检查3种不同情况,同时修改addLast()
和removeLest()
。
public final class TestList<E> {
private Node<E> head;
private Node<E> tail;
public void addLast(E data) {
Node<E> node = new Node<>(data);
if (head == null)
head = tail = node;
else if (head == tail) {
tail = node;
head.next = tail;
tail.prev = head;
} else {
tail.next = node;
node.prev = tail;
tail = node;
}
}
public void removeLast() {
if (tail == null)
System.err.println("List is empty!");
else if (head == tail)
head = tail = null;
else {
Node<E> prev = tail.prev;
tail.prev = null;
tail = null;
tail = prev;
tail.next = null;
}
}
private static final class Node<E> {
E data;
Node<E> next;
Node<E> prev;
public Node(E data) {
this.data = data;
}
}
}