Click to See Complete Forum and Search --> : Problem in understanding a recursive method


Zulfi Khan
July 29th, 1999, 12:27 AM
Can somebody help me in understanding the addToList (class SimpleQueue) recursive method in the following code??

I particularly donot understand the "return N"
statement in that method.
In my view inth else part, it goes to the end of list & then the contructor of QNode is called which stores the data in the new element of queue. But what is the purpose of "return N"
statement?? How many times its being called??

Zulfi.

class QNode {

public String dataItem;
public QNode next;

public QNode(String entry){
dataItem = entry;
next = null;
}
}



class SimpleQueue {

QNode top;

public SimpleQueue() {
top = null;
}

public void addEntry(String entry) {
top = addToList(top, entry);
}

private QNode addToList
(QNode N, String entry){
if (N == null)
return new QNode(entry);
else {
N.next = addToList(N.next, entry);
return N;
}
}
}

DAVID DONG
July 29th, 1999, 07:14 AM
as your code :
public void addEntry(String entry) {
top = addToList(top, entry);
}
the addToList retunr the toppest QNode.
if before call addToList , the SimpleQueue.top is null, then construct a new QNode ,and return it
set top is the node.
if before call addToList, the SimpleQuere.top has
existed , so top is it. then return the top (N) directly.

so, hope helps.

This is from david dong.

Zulfi Khan
July 29th, 1999, 11:47 PM
What is meant by top? Does it mean the first element or the last element of list? If top means the first element then what is the need to modify top each time we store a new element in the list?
I feel the new element would be stored at the end of list & wont change top.

DAVID DONG
August 3rd, 1999, 10:00 AM
When the list have none node, then one top node
should be return when add first node. Later the top will not be changed as you say.


This is from david dong.

Zulfi Khan
August 5th, 1999, 05:53 AM
Thanks for your reply. I think my problem is solved.
Zulfi