I tried to print the stack elements of the Linked List Implementation.
But to print in the order of the stack itself I need a static variable in java.
public void display()
{
<STATIC> <here I need> LinkedListImp temp = this;
while(temp.next!=null)
{
temp=temp.next;
display();
}
System.out.println("\n\t"+ temp.element +"\n");;
}
But While declaring like this, I am getting an error.
I have implemented the display() in interface concept. Hence I cannot have display(LinkedListImp temp).
interface StackMethods
{
int pop();
void push(int numberint);
void display();
}
For example,
If the elements of stack is 1 then 2 then 3.
I didnt want the output as 1 2 3 or 1 (newline) 2 (newline) 3.
Rather I want as 3 (newline)
2 (newline)
1 (though it is not required to demonstrate a real stack)
Is there any other way to implement this?
If you want the value of
tempnot to be dependent on an instance ofdisplay()‘s parent class (LinkedListImp?), then you would need a static class variable. In Java thestatickeyword marks a variable that belongs to an entire class, not an individual instance. Static in Java creates a variable that is also known as a “class variable.” By definition a class variable can’t be local. To learn more about static variables see what the documentation has to say or check out this StackOverflow question that has the spec in an answer.But it looks like what you are trying to do is use a class’s instance, which means you don’t want a static variable. You absolutely want the value tied to the class.
To make it work, though, you need braces around both statements in your while loop. Otherwise you will get a program that loops through all the elements of the linked list and prints out just the last one. This is because in Java if a block statement (
if,else,for,while, etc.) is not followed by braces it treats only the next line as the contents of the block.To reverse the order here with a loop I’d use a StringBuilder and build up a string.
Based on your edit you have added a recursive call to the method, but this is not necessary with the loop. If you are doing recursion, remove the loop. In that case recursion acts as a loop. In that case simply print out the item after calling display with the next item for reverse order, or before for standard order.