轉載請註明出處:http://blog.csdn.net/xdz78
#include <stdio.h>
#include <stdlib.h>
//查找單鏈表中的特定元素,《數據結構與算法——c語言描述》 3.11 答案
int count;//全局變量自動初始化爲0
int m;//需要查找的元素大小
typedef struct student {
int data;
struct student *next;
}Node;
int search(Node *p){
if(p==NULL){
return count+1;
}
if(p->data==m){
return count+1;
}
else {
p=p->next;
count++;
search(p);
}
}
int main()
{
int n;//單鏈表的元素個數
scanf("%d",&n);
Node *p1,*p2,*head;
int i;
p1=(Node *)malloc(sizeof(Node ));
p2=p1;
head=p1;
scanf("%d",&p1->data);
for(i=0;i<n-1;i++){
p1=(Node *)malloc(sizeof(Node ));
scanf("%d",&p1->data);
p2->next=p1;
p2=p1;
}
p2->next=NULL;
//單鏈表創建完成
//分別用遞歸和非遞歸完成查找工作
scanf("%d",&m);//輸入需要查找的元素
//遞歸:
count=search(head);
if(count==n+1){
printf("未找到該元素!");
}
else {
printf("此元素在鏈表的第%d個",count);
}
return 0;
}