Stack implementation for nodes containing objects

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 
+7
java stack linked-list
source share
1 answer

Your implementation returns a Node object when pop is called, but Node still has a reference to the "next" position in the original stack.

When you create a new stack and you click a pop-up element, the original Node object is sent to drive with the original next link.

 listOfInts -----> { 5 } -> { 3 } -> { 4 } ^ newStack -> { 8 } -+ 

This is why the whole list appears in a new stack.

The solution is not to fully open the Node object. Instead of accepting Node in push , accept the data item and create your own Node . Instead of returning Node to pop and peek retrieve the data item from Node and return it. Thus, you cannot accidentally test the link to the next Node in the desired node.

+4
source share

All Articles