单链表元素定位(输出链表中元素的下标)

来源:互联网 发布:c语言程序生成exe文件 编辑:程序博客网 时间:2024/06/05 03:13

6-2 单链表元素定位(12 分)

本题要求在链表中查找第一个数据域取值为x的节点,返回节点的位序。L是一个带头结点的单链表,函数ListLocate_L(LinkList L, ElemType x)要求在链表中查找第一个数据域取值为x的节点,返回其位序(从1开始),查找不到则返回0。例如,原单链表各个元素节点的元素依次为1,2,3,4,则ListLocate_L(L, 1)返回1,ListLocate_L(L, 3)返回3,而ListLocate_L(L, 100)返回0。

函数接口定义:

int ListLocate_L(LinkList L, ElemType x);

其中 L 是一个带头节点的单链表。 x 是一个给定的值。函数须在链表中查找第一个数据域取值为x的节点。若找到则返回其位序(从1开始),找不到则返回0。


#include <stdio.h>#include <stdlib.h>#include <malloc.h>using namespace std;#define TRUE        1#define FALSE       0#define OK          1#define ERROR       0#define INFEASIBLE  -1#define OVERFLOW    -2typedef int ElemType;typedef int Status;#define LIST_INIT_SIZE 100#define LISTINCREMENT 10;typedef struct LNode{   ElemType data;   struct LNode *next;}*LinkList,LNode;Status InitList(LinkList &L,ElemType n){    LNode *rea,*tmp;    L = (LNode *)malloc(sizeof(LNode));    L->next=NULL;    rea=L;    for(int i=0;i<n;i++){        ElemType m;        scanf("%d",&m);        tmp=(LNode*)malloc(sizeof(LNode));        tmp->data=m;        if(!tmp) exit(OVERFLOW);        rea->next=tmp;        rea=tmp;    }    rea->next=L;    return OK;}void ListLocate_L(LinkList L,ElemType n){    LNode *p=L;    int k=0;    while(p->next){        if(p->data==n){            printf("该元素的下标为%d\n",k);            return;        }        else{            p=p->next;            k++;        }        if(p==L){            printf("未找到该元素!\n");            return;        }    }}void print_LinkList(LinkList &L){    LNode *p=L->next;    if(p==L){        printf("Empty List!");        return;    }    while(p!=L){        if(p->next==L)            printf("%d\n",*p);        else            printf("%d ",*p);        p=p->next;    }}int main(){    int n;    LinkList L;    scanf("%d",&n);    if(InitList(L,n)){        printf("创建成功!\n");    }    else{        printf("创建失败!\n");    }    int m1,m2;    scanf("%d",&m1);    ListLocate_L(L,m1);    print_LinkList(L);    return 0;}


原创粉丝点击