我知道这个主题已被打败,但我真的很难将这两个添加方法实现到链表中。 addFirst和addLast都可以在自己调用时工作,但是当我调用addFirst(“foo”)和addLast(“bar”)时,add last会删除以前添加到列表中的任何内容。 add first应该是一个项目添加到列表的开头,而last 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("");
}
答案 0 :(得分:0)
好像你让自己感到困惑。一般来说,如果你做something.next.next
或类似的事情,你的头脑中就会发出警告。您也可以提供一个构造函数,该构造函数可以接受项目而不是方法中的addition语句。
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++;
}
答案 1 :(得分:0)
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++;
}
答案 2 :(得分:-1)
我认为这个问题可以通过一个简单的链接来回答 - 无论你的目标服务于什么教育目的,你都会重新发明总是一个坏主意的轮子。