链表结点的查找
**目标**:在一个单项链表中(所有数据不重复)中查找值为key的结点。并返回节点地址,若未找到返回NULL
方法一:
注意:本题要求返回所查找元素key的结点地址,故输出时直接输出地址即可。
遍历链表,一一比对p->data值是否等于所要查找元素key,若找到,则返回找到元素的地址,若未找到,则输出"您查找的数值不存在。"
代码实现:
Elensn* find(Elensn* h,int key)//传递首地址和要查找元素
{
Elensn *pfind=NULL,*p;
for(p=h;p->next!=NULL;p=p->next)
if(p->data==key)
pfind=p;
return(pfind);
}
方法二:
和方法一思想相同,运用了for的空循环,使链表的查找更为简便。
代码实现:
Elensn* find(Elensn* h,int key)
{
Elensn *p;
for(p=h;p&&p->data!=key;p=p->next);
return(p);
}
具体代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 6
typedef struct Node
{
int data;
struct Node *next;
}Elensn;
Elensn *initLink(int *a,int n)
{
int i;
Elensn *h=NULL,*tail;
h=tail=(Elensn*)malloc(sizeof(Elensn));
h->data=a[0];
h->next=NULL;
for(i=1;i<n;i++)
{
tail=tail->next=(Elensn*)malloc(sizeof(Elensn));
tail->data=a[i];
tail->next=NULL;
}
return h;
}
void printLink(Elensn* head)
{
Elensn* p;
for(p=head;p!=NULL;p=p->next)
printf("%d\t",p->data);
printf("\n");
}
Elensn* findkey(Elensn* h,int key)
{
Elensn *pfind=NULL,*p;
for(p=h;p->next!=NULL;p=p->next)
if(p->data==key)
pfind=p;
return pfind;
}
int main(void)
{
int a[N]={1,2,3,4,5,6},key;
Elensn * head,*pfind;
printf("请输出要查找的内容key\n");
scanf("%d",&key);
head=initLink(a,N);
pfind=findkey(head,key);
if(pfind)
printf("所查找key的地址为:%x\n",pfind);
else
printf("您查找的数值不存在。");
return 0;
}
实现效果: