單鏈表的查找和取值-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\n",i);
        }else{
                printf("There is no search data in the L!\n");
        }
        printf("Output the datas:");
        TraverseList_L(L);
        printf("\n");
}
結果:
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





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM