单链表的查找和取值-1

问题1:查找是否存在第i个元素,若存在用e返回第i个元素的值。不然返回0

查找部分算法:

(1)从第一个结点(L->next)顺链扫描,用指针指向当前扫描到的节点,p初值p=L->next

(2)定义j作为计数器,累计当前扫描到的结点数,初值为1

(3)当p指向扫描到下一个节点时,计数器加1;

(4)开始循环,循环条件是p不为空和j<i;当j=i和p不为空时说明找到第i个元素

(5)当p为空或者j>i时说明第i元素不存在。

代码:

#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;
}

//若表中存在第i个元素,由变量e带回其值
int GetElem_L(LinkList L,int i,int &e){
        LinkList p;
        int j=0;
        p=L;
        while(p&&j<i){    //查找第i个元素
                p=p->next;
                ++j;
        }
        while(!p||j>i){
                return ERROR;
        }
        e=p->data;
        return OK;
}

//遍历单链表L
int TraverseList_L(LinkList L){
        LinkList p;
        p=L->next;
        while(p){
                printf("%d",p->data);
                p=p->next;
        }
        return OK;
}
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 location:");
        scanf("%d",&i);
        if(GetElem_L(L,i,e)){
                printf("The data in the location %d is %d\n",i,e);
        }else{
                printf("Can't find the right location!\n");
        }
        printf("Output the datas:");
        TraverseList_L(L);
        printf("\n");
}

结果:
android@android-Latitude-E4300:~/work/c/danlianbiao$ ./getelemlist
Input the length of the list L:5
Input the datas:1 3 5 7 9
Input the search location:3
The data in the location 3 is 5
Output the datas:13579




 

posted @ 2017-05-25 14:12  狼太白  阅读(719)  评论(0编辑  收藏  举报