[英]Why is my doubly linked list removing previous links?
我知道這個主題已被淘汰,但是我真的很難實現這兩個添加方法到鏈表中。 當自己調用addFirst和addLast時,它們都可以工作,但是當我調用addFirst(“ foo”)和addLast(“ bar”)時,最后添加會刪除以前添加到列表中的所有內容。 首先添加應該將一個項目添加到列表的開頭,最后添加應該將其添加到列表的末尾。
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Deque<Item> implements Iterable<Item> {
private int N;
private Node first;
private Node last;
//create linked list
private class Node
{
String item;
Node next;
Node previous;
}
public Deque() // construct an empty deque
{
N = 2;
first = new Node();
last = new Node();
//link together first and last node;
first.next = last;
last.previous = first;
last.item = "Last";
first.item = "First";
}
public boolean isEmpty() // is the deque empty?
{
return first == null;
}
public int size() // return the number of items on the deque
{
return N;
}
public void addFirst(Item item) // insert the item at the front
{
Node nextElement = new Node();
nextElement.item = (String)item;
nextElement.next = first.next;
nextElement.previous = first;
first.next = nextElement;
N++;
}
public void addLast(Item item) // insert the item at the end
{
Node newLast = new Node();
newLast.item = (String)item;
newLast.next = last;
newLast.previous = last.previous;
last.previous.next = newLast;
last.previous = newLast;
N++;
}
public void printList()
{
Node print = first;
for (int i = 0; i < N; i++)
{
System.out.print(print.item);
print = print.next;
}
System.out.println("");
}
似乎讓您感到困惑。 通常,如果您正在執行something.next.next
或類似操作,則應該在您的腦海中發出警告。 您也將很樂意提供一個可以使用項目而不是方法中的additional語句的構造函數。
public void addLast(Item item) // insert the item at the end
{
Node newLast = new Node();
newLast.item = (String)item;
if (isEmpty()) {
first = newLast;
} else {
last.next = newLast;
newLast.previous = last;
}
last = newLast;
N++;
}
就addFirst
而言,因此您不會無意間得到錯誤的建議,它將像這樣...
public void addFirst(Item item) {
Node newFirst = new Node();
newFirst.item = (String)item;
if (isEmpty()) {
last = newFirst;
} else {
first.previous = newFirst;
}
newFirst.next = first;
first = newFirst;
N++;
}
addfirst方法缺少更新指針之一
public void addFirst(Item item) // insert the item at the front
{
Node nextElement = new Node();
nextElement.item = (String)item;
nextElement.next = first.next;
nextElement.previous = first;
first.next.previous = nextElement; //ADDED HERE
first.next = nextElement;
N++;
}
我認為這個問題可以通過一個簡單的鏈接來回答-無論您的目標是出於什么教育目的,您都在重新發明輪子,這始終是一個壞主意。
使用Deque
接口 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.