| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1417 人关注过本帖
标题:新手线性表 LocateElem中 compare 定义?
只看楼主 加入收藏
啊忠
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2011-10-17
收藏
 问题点数:0 回复次数:1 
新手线性表 LocateElem中 compare 定义?
#include<stdio.h>
#include<stdlib.h>
#define LIST_INIT_SIZE 30
#define LISTINCREMENT 10
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct{
    ElemType *elem;
    int length;
    int listsize;
}SqList;
Status InitList(SqList *pL){
    (*pL).elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
    if(!(*pL).elem) return OVERFLOW;
    (*pL).length=0;
    (*pL).listsize=0;
    return OK;
}
int ListLength(SqList *pL){
    return pL->length;
}

void GetElem(SqList *pL,int i,ElemType *e)
{
    if((i>=1)&&(i<=(*pL).length))
        *e=(*pL).elem[i-1];
   
}
Status ListInsert(SqList *pL,int i,ElemType e)
{
    int *p,*q,*newbase;
    if(i<1||(i>(*pL).length+1))
        return ERROR;
    if((*pL).length>=(*pL).listsize)
    {    newbase=(int *)realloc((*pL).elem,(LIST_INIT_SIZE+LISTINCREMENT)*sizeof(ElemType));
        if(!(newbase)) return OVERFLOW;
        (*pL).elem=newbase;
        (*pL).listsize+=LISTINCREMENT;
      }
    p=&((*pL).elem[i-1]);
    q=(*pL).elem+(*pL).length-1;
    for(q;q>=p;--q)
        *(q+1)=*q;
    *p=e;
    ++(*pL).length;
    return OK;
}

int compare(ElemType * e1, ElemType * e2)
{//测试函数,返回要查找的元素
    return (*e1 - *e2);
}

int LocateElem(SqList *pL,ElemType e,int (*compare)(ElemType *,ElemType *))
{
    int i;
    ElemType *p;
    i=1;
    p=(*pL).elem;
    while (i<=(*pL).length&&(*compare )(p++ ,&e))
        ++i;
    if(i<=(*pL).length)
        return i;
    else return 0;
}

初学数据结构,对红色部分写法不懂,蓝色部分上网找的 compare 定义,老师没讲 compare中 return (*e1 - *e2); 很不理解啊,这什么用,看了好久也看不懂。谁教教我 compare 简单的定义 有吗  大家帮帮哦
搜索更多相关主题的帖子: compare 线性表 return include 
2011-10-17 20:28
leizisdu
Rank: 2
等 级:论坛游民
帖 子:22
专家分:24
注 册:2011-10-17
收藏
得分:0 
回复 楼主 啊忠
红色部分是一个指向函数的指针,做函数LocateElem的参数,它指向的函数有两个参数,参数类型是ElemType *,而且它指向的函数有返回值,返回值类型是int型。
蓝色部分compare函数体:return (*e1 - *e2);所以,如果(*e1 == *e2)则函数返回值等于0,其他情况返回值不等于0。函数LocateElem中:
while (i<=(*pL).length && (*compare)(p++, &e)) ++i;
当i<=(*pL).length同时compare函数返回0时,while循环也会退出,表明在线性表中找到了e。
我也是新手,不知道说的对不对,你看看是这样吗?
2011-10-18 22:25
快速回复:新手线性表 LocateElem中 compare 定义?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015951 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved