Daniel said:
Is that function OK now? However, is there any better method to do so,
because I think my coding seems quite dirty and long to solve such
simple task.
void RemoveNode(StepNodePtr pList)
{ StepNodePtr preq, q;
int i;
q = pList;
preq = pList;
//CountStep(q) is another function which return the number
//of node in the linked list
i=CountStep(q);
You don't need to count them to know if there's zero or one.
If there's zero, pList will be NULL:
if (pList == NULL)
return;
If there's one, pList->next will be NULL:
if (pList->next == NULL) {
free(pList);
return;
}
if (i!=0 && i!=1))
{
while (q->next!=NULL)
{ q=q->next;
}
while (preq->next!=q) {
preq = preq->next;
}
preq->next = NULL;
The purpose of this is to remove the last node, I surmise? Instead of
finding the last node, then finding the one before that, how about finding
the next-to-last right away?
while (q->next->next) {
q = q->next;
}
free(q->next);
q->next = NULL;
}
if ((CountStep(q)!=0))
free(q);
With your original code, q is the last node, which means it should always be
0, right?
assert(!q->next); /* requires assert.h */
free(q);
}
By the way, after I solve the problem of the RemoveNode() function, I
got another error message which is also "Access Violation" from the
another function "isVisited()" However, I think all the cases are
handled already as this is just as simple as the traverse list
function. Could you please kindly tell me the problem of my function?
Thanks
int isVisited(StepNodePtr pList, int x, int y)
{ StepNodePtr p=pList;
while (p!=NULL)
{ if (p->data.x==x && p->data.y==y)
return 1;
p=p->next;
}
return 0;
}
This function seems okay to me, probably your list was corrupted elsewhere.
That said, you don't need the local variable p, you can just use pList
(though with modern optimizing compilers it probably won't matter)