I have a question on which algorithm is more efficient (time & space) on solving this singly linked list problem:
#1:
Have one pointer go through and find the size of the list,
have another go through until it is at node size-m
#2:
Have one pointer go up to the mth node,
now have another pointer start at first node;
increment both pointers until the first has reached the end. The second one is now at the mth to last node.
Would #2 be faster than #1, or would they be of the same speed?
Also, for the following function which implements alg.#2, instead of initializing a second pointer, could I just use head?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
Node *mToLast( Node *head, int m)
{
Node *first; //Do I need Node *second ?
int count;
while (count != m) {
first= first->next;
count++;
}
while (first != null) {
first= first->next;
head= head->next; //Can I use head like this?
}
return head;
}
|
Also, when the above function is finished, the original head node pointer (which was passed in) will be unchanged, right? (because only a copy of the pointer is being passed into the function...)
thank you very much!