Two ways. 1:record the length of the linked list, then go n-k steps. 2: use two cursors.Time complexities are exactly the same.Node * lastK(Node * head, int k) { if (k<0) error(“k < 0”); Node *p=head, *pk=head; for (;k>0;k--) { if (pk->next!=NULL) pk =pk->next; else return NULL; } while (pk->next!=NULL) { p=p->next, pk=pk->next; } return p;}
共 1 个关于本帖的回复 最后回复于 2013-8-16 11:09