2.2

来源:互联网 发布:内存卡怎么恢复数据 编辑:程序博客网 时间:2024/05/16 07:10

Implement an algorithm to find the nth to last element of a singly linked list.

分析:查找链表倒数第n个元素,这在剑指offer上有相同的习题

Node* get_lastn(Node* head,int n){if(head==NULL||n<=0) return NULL;Node* front=head;Node* behind=head;while(n>1){behind=behind->next;if(behind==NULL) return NULL;n--;}while(behind->next!=NULL){front=front->next;behind=behind->next;}return front;}