Re: Newbie Question: Why use a current pointer in a linked list?
On Mar 26, 9:50 am, themas...@yahoo.com wrote:
In the texts I am learning from they always have a 'current pointer'
inside functions which manipulate the linked list. (http://
cslibrary.stanford.edu/105/) I detected no memory leaks (using
_CrtDumpMemoryLeaks in VC++). And the disassembly is the same expect
the version without Current pointers uses less memory. I have searched
for a concise reason for using a current pointer and not found a
reason.
Some people find code easier to read if the function parameters
aren't modified. In this case, even more probable find using
different names makes the code easier to read; there is a lot to
say for calling the parameter "head", or "begin", but using the
word "current" in the name of the variable which changes. And
it makes no real difference in memory usage; nothing that could
possibly affect a real program, at any rate.
Having said that, the code in question doesn't look very
idiomatic for C++, and makes me wonder about the quality of the
learning material. (The interface looks very clunky, too. But
that may be just because they are trying to use a C-like idiom,
to teach algorithms, and are ignoring objects for the moment.)
//This is a copy list function using a current pointer.
NODE * CopyListUsingCurrent(NODE * headRef)
There should definitly be a const after the second NODE*, here.
{
NODE * currentNode=NULL;
And after the first here.
currentNode = headRef;
And of course, anyone even slightly familiar with C/C++ would
have written these two statements as one.
NODE * newHead = NULL;
NODE ** tail = &newHead;
while(currentNode)
Whereas people concerned with readability would normally write
this as:
while ( currentNode != NULL )
A lot of C/C++ will use the shorter form, above (but their code
won't pass code review anywhere I've worked). But such people
would be striving for an idiomatic C/C++, and would not insist
on two separate variables for the current and the head. So it
looks very strange.
{
Push(tail,currentNode->data);
tail= &((*tail)->next);
currentNode = currentNode->next;
}
return newHead;
}
// I removed the current pointer in this version. So why not just do
this?:
NODE * CopyList(NODE * headRef)
{
//NODE * currentNode=NULL;
//currentNode = headRef;
NODE * newHead = NULL;
NODE ** tail = &newHead;
while(headRef)
{
Push(tail,headRef->data);
tail= &((*tail)->next);
headRef = headRef->next;
}
return newHead;
}
Basically, because the variable called headRef doesn't always
point to the head. It's a naming problem, that's all.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]