单链表的查找和取值-2

问题2:根据制定数据获取所在的位置

找到则返回值,不然返回0

算法: (1)从第一个结点起,依次与e相比较

   (2)找到一个其值与e相等的数据元素,则返回其在链表中的“位置” 》这里循环条件是p不为空,以及p->data不等于e

   (3)如果查遍整个链表没有与e相等是元素,则返回0

代码:

#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct LNode{
        int data;
        struct LNode *next;
}LNode,*LinkList;
//建立一个只含头结点空链表
int InitList_L(LinkList &L){
        L=(LinkList)malloc(sizeof(LNode));
        if(!L){
                exit(OVERFLOW); // 存储分配失败
        }
        L->next=NULL;
        return OK;
}

//建立含n个元素的单链表,并且是尾插入,
int CreateList_L(LinkList &L,int n){
        LinkList p,q;
        int i;
        printf("Input the datas:");
        q=L;
        for(i=0;i<n;i++){
                p=(LinkList)malloc(sizeof(LNode));
                scanf("%d",&p->data);
                p->next=q->next;
                q->next=p;
                q=p;
        }
                return OK;
}

//线性表L中查找e的数据元素,成功返回数据元素的位置序号,失败返回0
int LocateElem_L(LinkList L,int e){
        LinkList p;
        int j=0;
        p=L;
        while(p&&p->data!=e){
                p=p->next;
                ++j;
        }
        if(p){
                return j;  //成功的查找返回元素的位置
        }else{
                return OK; //失败,返回0
        }
}
main(){
        int i,n,e;
        LinkList L;
        InitList_L(L);
        printf("Input the length of the list L:");
        scanf("%d",&n);
        CreateList_L(L,n);
        printf("Input the search number:");
        scanf("%d",&e);
        i=LocateElem_L(L,e);//返回位置
        if(i){
                printf("The search data is in the %dth location in the L ",i);
        }else{
                printf("There is no search data in the L! ");
        }
        printf("Output the datas:");
        TraverseList_L(L);
        printf(" ");
}
结果:
android@android-Latitude-E4300:~/work/c/danlianbiao$ ./LocateElem
Input the length of the list L:5
Input the datas:1 3 5 7 9
Input the search number:5
The search data is in the 3th location in the L
Output the datas:13579




原文地址:https://www.cnblogs.com/shamoguzhou/p/6903713.html