1、试写一算法在带头结点的单链表结构上实现线性表操作Locate(L,x)
2、试写一算法在带头结点的单链表结构上实现线性表操作Length(L)
C code:
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define OVERFLOW -1
#define TRUE 1
typedef int Status;
struct LNode
{
int data;
LNode *next;
};
typedef LNode *LinkList;
void InitList(LinkList &L)
{
L=(LinkList)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next=NULL;
}
int ListLength(LinkList L)
{
int i=0;
LinkList p=L->next;
while(p)
{
i++;
p=p->next;
}
return i;
}
int LocateElem(LinkList L,int e)
{
int i=0;
LinkList p=L->next;
while(p)
{
i++;
if(p->data==e)
return i;
p=p->next;
}
return 0;
}
void CreateList(LinkList &L,int n)
{
int i;
LinkList p,q;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
q=L;
printf("Please input %d numbers:\n",n);
for(i=1; i<=n; i++)
{
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
q->next=p;
q=q->next;
}
p->next=NULL;
}
void judge(LinkList L,int x)
{
int flag;
flag=LocateElem(L,x);
if(flag)
printf("elem %d is in the %d place of L",x,flag);
else
printf("elem %d is not in L",x);
}
void PrintList(LinkList L)
{
LinkList p;
p=L->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
LinkList L;
int len,x;
CreateList(L,8);
printf("LinkList L:");
PrintList(L);
len=ListLength(L);
printf("The LinkList L'length is:%d\n",len);
printf("input number x:");
scanf("%d",&x);
judge(L,x);
return 0;
}
#define ERROR 0
#define OK 1
#define OVERFLOW -1
#define TRUE 1
typedef int Status;
struct LNode
{
int data;
LNode *next;
};
typedef LNode *LinkList;
void InitList(LinkList &L)
{
L=(LinkList)malloc(sizeof(LNode));
if(!L)
exit(OVERFLOW);
L->next=NULL;
}
int ListLength(LinkList L)
{
int i=0;
LinkList p=L->next;
while(p)
{
i++;
p=p->next;
}
return i;
}
int LocateElem(LinkList L,int e)
{
int i=0;
LinkList p=L->next;
while(p)
{
i++;
if(p->data==e)
return i;
p=p->next;
}
return 0;
}
void CreateList(LinkList &L,int n)
{
int i;
LinkList p,q;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
q=L;
printf("Please input %d numbers:\n",n);
for(i=1; i<=n; i++)
{
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
q->next=p;
q=q->next;
}
p->next=NULL;
}
void judge(LinkList L,int x)
{
int flag;
flag=LocateElem(L,x);
if(flag)
printf("elem %d is in the %d place of L",x,flag);
else
printf("elem %d is not in L",x);
}
void PrintList(LinkList L)
{
LinkList p;
p=L->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
LinkList L;
int len,x;
CreateList(L,8);
printf("LinkList L:");
PrintList(L);
len=ListLength(L);
printf("The LinkList L'length is:%d\n",len);
printf("input number x:");
scanf("%d",&x);
judge(L,x);
return 0;
}