I have a LinkedList of Nodes that contain Integer Objects.
LinkedList listOfInts = new LinkedList();
And I add 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,
Node p = listOfInts.pop()
And then print the data,
System.out.println(p.getData());
I get the correct answer: 8.
But if I want to push this number to the new LinkedList ;
LinkedList newStack = new LinkedList(); newStack.push(p);
It pops all listOfInts, not just the first data point, 8.
[8,5,3,4]
My question is, why is this happening? Since this is such a basic problem, I assume that it is related to my push() and pop() methods, but since I wrote them the same way as I saw in the textbooks, I donβt know what is wrong with them. Can someone 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: as suggested with returning objects instead of Nodes , and the code is more or less the same except for the push() method. Therefore, 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