返回线性链表的倒数第n个元素
Implement an algorithm to find the nth to last element of a singly linked list
分析:
想法很简单,但是不是一下子就能想到的: 两个指针p1,p2分别指向头节点,然后让p1先循环n-1次,这样p1与p2 的间隔就是n-1,然后同时增加p1,p2,当p2到达尾节点的时候,p1正好到达倒数地n个节点。
Linklist nthToLast(Linklist L,int n) { if(L==NULL||n<1) return NULL; Linklist p1=L; Linklist p2=L; for(int j=0;j<n-1;j++) { if(p2==NULL) return NULL; p2=p2->next; } while(p2->next!=NULL) { p1=p1->next; p2=p2->next; } return p1; }