#include<stdio.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void print(struct LNode* L)
{
L=L->next;
while(L)
{
printf("%d ",L->data);
L=L->next;
}
printf("\n");
}
LNode *LocateElem(LinkList L,int e){
LNode *p=L->next;
while(p!=NULL&&p->data!=e)
p=p->next;
return p;
}
LinkList List_HeadInsert(LinkList &L){
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode*s,*r=L;
scanf("%d",&x);
while(x!=9999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
int main(){
int n;
LNode headNode;
headNode.next = NULL;
LinkList L;
L = &headNode;
printf("请输入单链表的值:");
List_HeadInsert(L);
print(L);
printf("你想要查找的元素:");
scanf("%d",&n);
LNode *num=LocateElem(L,n);
if(num==NULL)
printf("查找失败,此单链表中没有这个元素");
printf("查找成功,这个元素为%d:",num->data);
return 0;
}
核心代码:
LNode *LocateElem(LinkList L,int e){
LNode *p=L->next;
while(p!=NULL&&p->data!=e)
p=p->next;
return p;
}