开发者

Java: implementing a list

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();开发者_开发知识库
  }
}


In this block:

public void push(int i)
{
  stuff = i;
  next = this;
}

You are assigning the node's next to itself.

Try this instead:

public void push(int i)
{
  next = new Cons(i);
}

That will remove the self-loop, but then you will still have the problem of remembering where the tail is. I will leave that as an exercise, since this is homework.

Another problem, pointed out in a comment, is that your code shouldn't compile as is, because you are attempting to call a constructor that doesn't exist.

If you want to call this(i, null) you need a constructor that takes (int, Cons) as its arugments.


Try to create code as shown in wikipedia. You need Container to hold nodes, and Node to represent single node in list


I think

next = this

is wrong, you should instead create a new entry

next = new Cons(stuff);
stuff = i;

otherwise the next entry will point to the current one! Note that the order of the elements is reversed if you do it that way..


public void push(int i)
{
  stuff = i;
  next = this; //here's the problem.
}

You need something like:

public void push(int i)
{
  Cons newnext = new Cons(i)
  tail.next = newnext;
  tail = newnext;
}

and of course you need a reference to the tail of your linked list somewhere.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜