0

I got a question. I am given a linked-list Node with the parameter of A val and Node next. I also given a function call join which will join the end of list x to to y.

5 |-> 6 |-> 7 |-> null

Node x = new Node(5, new Node(6, new Node(7, null))); 
this.join(x, x) 
 public void join(Node x, Node y){
 if(x.next==null){
 x.next = y;
 }else{
 join(x.next, y);
 }
}

and when I get the length is only 3. Can I how come is not a stack overflow instead?

Jigar Joshi
241k42 gold badges409 silver badges446 bronze badges
asked Nov 22, 2010 at 11:20
1
  • 2
    Can we see the length() method? Commented Nov 22, 2010 at 11:30

3 Answers 3

1

how come is not a stack overflow instead?

Because the list still has an end before the call to join() terminates. If you call it again, however...

answered Nov 22, 2010 at 11:29
Sign up to request clarification or add additional context in comments.

1 Comment

Hi thanks for the reply. I check again and it turn out to be overflow.
1

The join function looks good, but if you invoke it with this.join(x,x) you build some kind of circle!

So if you do something recursive with x after this.join(x,x), you will possible get some kind of stack overflow because of an endless recusrion.

answered Nov 22, 2010 at 11:32

1 Comment

Hi! thanks for your reply and it indeed turn into an overflow.
1

Because there is only one instance of node x, and you build up circle in your list. You will never reach x.next==null. You should probably check for some equality.

answered Nov 22, 2010 at 11:37

1 Comment

Hi thanks.You are right! it was my code that was the problem.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.