包含对象的节点的堆栈实现
我有一个包含Integer对象的Nodes LinkedList 。
LinkedList listOfInts = new LinkedList();
我添加Objects ;
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(3));
list.add(new Integer(4));
与以下Node类:
class Node {
private Object data;
private Node next;
public Node(Object data)
{
this.data = data;
this.next = next;
}
public Object getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next = next;
}
}
如果我做这样的事情;
Node p = listOfInts.pop()
然后打印数据,
System.out.println(p.getData());
我得到正确的答案:8。
但是如果我想把这个数字推到一个新的LinkedList ;
LinkedList newStack = new LinkedList();
newStack.push(p);
它推动整个listOfInts,而不仅仅是第一个数据点8。
[8,5,3,4];
我的问题是为什么会发生? 既然这是一个基本问题,我认为它与我的push()和pop()方法有关,但是因为我写的类似于我在教科书中看到的那些,所以我不知道它们有什么问题。 任何人都可以帮助我理解?
public Node pop()
{
Node item = peek(); //save item to return
if(!isEmpty())
{
first = first.getNext(); //delete first node
}
size--;
return item; //return first saved item
}
public void push(Node item)
{
Node next = item.getNext();
next = first;
first = item;
size++;
}
public Node peek()
{
if (isEmpty())
{
System.out.println("Error: No element");
}
return first;
}
编辑:建议与返回的对象,而不是Nodes ,代码是或多或少相同,除了push()方法。 所以,当我尝试将另一个对象添加到同一个LinkedList ,它会替换旧的而不是添加到列表中。
//push node on top of the stack
public void push(Object item)
{
Node newNode = new Node(item);
Node next = newNode.getNext();
next = first;
first = newNode;
size++;
}//push
您的实现在调用pop时返回Node对象,但Node仍然引用原始堆栈中的“next”位置。
当你创建一个新的堆栈,并且你推动弹出的项目时,最初的next参考是原来的Node对象。
listOfInts -----> { 5 } -> { 3 } -> { 4 }
^
newStack -> { 8 } -+
这就是为什么整个列表出现在新的堆栈上。
该解决方案根本不公开Node对象。 不要接受push的Node ,接受数据项并创建自己的Node 。 而不是返回的Node在pop和peek ,提取从数据项Node ,并将其返回。 通过这种方式,您不会无意中冒险泄露对所需节点中下一个Node的引用。
上一篇: Stack Implementation for Nodes containing Objects
下一篇: Find minimum cost to convert array to arithmetic progression
