本文参考该作者文章当作编程笔记: 作者:Hawstein 出处:http://hawstein.com/posts/ctci-solutions-contents.html
Q:实现一个算法从一个单链表中返回倒数第n个元素。
思路:
findNthRecursion(link):递归的调用单链表的下一个节点,直到到达链表的尾部。此时,开始计数,直到到倒数第nn个数时,返回此时的h,即pp。
缺点是需要定义两个全局变量。
link findNthToLast(link,int):定义两个指针p和q,使p和q之间差距n个距离,当p指向NULL时,q就指向了倒数第n个数。
Talk is cheap,Show me CODE:
- list.h接口
1 typedef struct node *link; 2 typedef int itemType; 3 struct node{itemType item;link next;}; 4 void initNodes(link,itemType [],int);
- list.c实现
#include<stdlib.h> #include"list.h" void initNodes(link h,itemType s[],int n) { link p=h; int i; for(i=0;i<n;i++) { p->next=malloc(sizeof(struct node)); p=p->next; p->item=s[i]; p->next=NULL; } }
- 客户程序
1 #include<stdio.h> 2 #include"list.h" 3 #define N 10 4 struct node head; 5 link pp=NULL; 6 int nn; 7 void findNthRecursion(link h) 8 { 9 if(h==NULL)return; 10 findNthRecursion(h->next); 11 if(nn==1)pp=h; 12 nn--; 13 } 14 link findNthToLast(link h,int n) 15 { 16 if(h==NULL||n<1)return NULL; 17 link p=h,q=h; 18 while(n>0&&p) 19 { 20 p=p->next; 21 n--; 22 } 23 if(n>0)return NULL; 24 while(p) 25 { 26 p=p->next; 27 q=q->next; 28 } 29 return q; 30 } 31 int main() 32 { 33 int s[N]={1,2,3,4,5,6,7,8,9,0}; 34 initNodes(&head,s,N); 35 link p=findNthToLast(&head,6); 36 if(p)printf("%d ",p->item); 37 nn=6; 38 findNthRecursion(&head); 39 if(pp)printf("%d ",pp->item); 40 return 0; 41 }