#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList initList();
int insertList(LinkList head, int pos, ElemType e);
int GetIndex(LinkList head, ElemType e);
//初始化
LinkList initList()
{
LNode *H;
H=(LNode*)malloc(sizeof(LNode));
if(!H)return NULL;
H->next=NULL;
return H;
}
//插入
int insertList(LinkList head, int pos, ElemType e)
{
if(pos<1)return 0;
LNode *p=head,*s;
int j;
for(j=1;j<pos;j++)
{
if(p->next==NULL)return 0;
p=p->next;
}
s=(LNode*)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return 1;
}
//删除
int deleteList(LinkList head, int pos ,ElemType *e)
{
if(pos<1)
{
printf("error\n");
return 0;
}
LNode *p=head;
int i;
for(i=1;i<pos&&p->next!=NULL;i++)
p=p->next;
if(p->next==NULL||i>pos)
{
printf("error\n");
return 0;
}
LNode* q=p->next;
p->next=q->next;
printf("%d\n",q->data);
free(q);
return 1;
}
//补充查找算法:若找到返回e在链表中位置,未找到返回0
int getIndex(LinkList head, ElemType e)
{
LNode*p=head,*s;
int j=0;
while(p->next!=NULL)
{
p=p->next;
j++;
if(p->data==e)return j;
}
return 0;
}
//输出链表
void printList(LinkList head)
{
LNode *p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
LinkList head;
ElemType e;
int i,n;
scanf("%d",&n);
head=initList();
//用insertList函数的建表方法
for(i=0;i<n;i++)
{
scanf("%d",&e);
insertList(head,i+1,e);
}
//不用insertList函数的建表方法
/*LNode *p,*p1;
p=head;
for(i=1;i<=n;i++){
p1=(LNode*)malloc(sizeof(LNode));
scanf("%d",&e);
p1->data=e;
p1->next=NULL;
p->next=p1;
p=p->next;
}*/
//补充代码,实现若干个关键字值得查找
char b;int f=1,a=0;
while(1)
{
b=getchar();
if(b>='0'&&b<='9')
{
a=a*10+(int)b-48;
f=2;
}
else if(b=='-')f=0;
else if(b=='\n'||b==' ')
{
if(!f)a=a*(-1);
if(!f&&a==0)break;
if(a!=0||f==2)
{
i=getIndex(head,a);
if(i)printf("%d\n",i);
else printf("no\n");
}
a=0;f=1;
}
else break;
}
return 0;
}
单链表实现
最新推荐文章于 2024-05-23 14:39:06 发布