I have a LinkedList of Nodes that contain Integer Objects.
LinkedList listOfInts = new LinkedList();
And I add the Objects;
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(3));
list.add(new Integer(4));
with the following Node class:
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;
}
}
If I do something as such;
Node p = listOfInts.pop()
And then print the data,
System.out.println(p.getData());
I get the right answer: 8.
But if I want to push this number onto a new LinkedList;
LinkedList newStack = new LinkedList();
newStack.push(p);
It pushes the entire listOfInts, not just the first data point, 8.
[8,5,3,4];
My question is why this happens? Since this is such a basic problem, I assume it has to do with my push() and pop() methods, but since I wrote them similar to ones I've seen in textbooks, I don't know what's wrong with them. Could anyone help me understand?
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;
}
EDIT: Did as suggested with returning Objects instead of Nodes, and code is more or less the same except for push() method. So, when I try to add another object to the same LinkedList, it replaces the old one instead of adding to the list.
//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