So I'm learning Java and I want to implement a singly-linked list, but when I try to print it, it goes into an infinite loop, printing only the first element, as if the temp
doesn't get reassigned. What's wrong here?
public class Cons
{
public int stuff;
public Cons next;
public Cons(int i)
{
this(i, null);
}
public void show()
{
Cons temp = this;
while(temp != null)
{
System.out.println(temp.stuff);
temp = temp.next;
}
}
public void push(int i)
{
stuff = i;
next = this;
}
public static void main(String[] args)
{
Cons head = new Cons(2);
head.push(3);
head.push(12);
head.show();
}
}