我知道这个话题已经被击败了,但我真的在努力实现这两个添加方法到一个链表。addFirst和addLast在自己调用时都可以工作,但是当我调用addFirst("foo")和addLast("bar")时,add last会删除以前添加到列表中的任何内容。Add first应该是在列表的开头添加一项,Add last应该是在列表的末尾添加一项。
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
或类似的事情,你的头脑中应该会发出警告。您还可以提供一个构造函数,该构造函数可以接受项而不是方法中的加法语句。
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
接口