Reputation: 201
I saw a question posted regarding linked lists and encountered a problem while trying to solve it and now I can't figure it out. Here are two of the classes:
if (part1.equals("add"))
{
test.addNext(num);
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
}
Here's the class that will set add nodes to the linked list
import java.util.List;
import javax.xml.soap.Node;
int count;
Set() {
front = null;
count = 0;
}
boolean isEmpty() {
return front==null;
}
int pop() {
int x = front.x;
front = front.next;
count--;
return x;
}
}
I can't seem to figure out why I can't get a list to print when the user inputs various integers. If I were to hard code it without getting user input, like so:
test.addNext(1);
test.addNext(7);
test.addNext(3);
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
I get this output:
3 7 1
Why can't I get the same results when I allow the user to input the integers? As the program currently stands, here is how the output looks like:
Enter command: add 1
1
Enter command: add 7
7
Enter command: add 3
3
Enter command:
When I would like the output to look like this:
Enter command: add 1
1
Enter command: add 7
7 1
Enter command: add 3
3 7 1
Enter command:
Upvotes: 0
Views: 53
Reputation: 10613
Your code to print the list is modifying it:
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
This removes items from the list until it's empty. This means that each time you print (after each new item being added), you immediately remove that item again. The difference between the case where you get user input and the hardcoded values is that you print after each new user entry, whereas you only print at the end of the hardcoded data.
So you'd see the same problem if you did your code like this:
test.addNext(1);
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
test.addNext(7);
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
test.addNext(3);
while(!test.isEmpty()){
System.out.println(test.pop() + " ");
}
And you would see the problem go away if you asked the user for all three items before printing the list.
With your current code, there's no way to examine all the nodes in the list without removing them (not considering re-adding them again after printing). I'd suggested writing a toString
method which will print every node, and doesn't remove anything. Something like this:
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
LinkedNode current = front;
while(current != null){
sb.append(current.x + " "); //Not an ideal solution, but demonstrates the right idea.
current = current.next;
}
return sb.toString();
}
Alternatively, you could implement get(int)
and size()
methods (or an iterator), and do a loop like this instead of your current while
loop:
for(int i = 0; i < test.size(); i++){
System.out.println(test.get(i) + " ");
}
Upvotes: 4