主题:大家帮忙哈!有关链表
顺序查找:
设有8个关键字序列k={ a1 , a2, a3 , a4 , a5 , a6 , a7 , a8 },使用链表作为存储方式,用顺序查找法在序列中查找key= a2和key=b的数据元素(b不存在于k中),如果查找成功,则返回该元素,并在链表中删除它,如果查找不成功,则在链表结尾处插入它作为新的数据元素。
#include <stdio.h>
struct list
{
int data;
struct list *next;
}*head,*p;
void create (struct list *head,int n) /* 初始化链表,长度为n */
{struct list *p,*s;
int i;
p=head;
printf("\nplease input the elem of linklist:\n");
for(i=1;i<=n;i++)
{s=(struct list *)malloc(sizeof(struct list));
scanf("%d",&s->data);
p->next=s;p=s;s->next=NULL;}
}
void delete (struct list *head,int i)/* 删除链表中第i个结点 */
{struct list *q,*p=NULL;
int k;
q=head;
if(i==1)
head->next=q->next->next;
else
{ p=head;
{for(k=1;k<i;k++)
p=p->next;}
p->next=p->next->next;
}
}
void printout (struct list *head)/* 输出链表中各个结点的数据域 */
{struct list *p;
p=head->next;
printf("\nthe elem of linklist are:\n");
while(p)
{printf("%5d",p->data);
p=p->next;}
printf("\n");
}
int locate(struct list *head,int e,int n)/*查询链表中数据为e的元素*/
{
struct list *p,*s,*q;
int i;
p=head;
while(p&&p->data!=e)
{for(i=1;i<=n;i++)
{p=p->next;
if(p==NULL){ printf("There is not this elem in this linklist!\n") ;
delete(head,i);return(i);
}
else {printf("The elem exits in this linklist!\n");
s=(struct list *)malloc(sizeof(struct list));
s->data=e;s->next=NULL;q=s;p->next=q;return(0);
}
}}}
main()
{struct list *head,*s;int n=8;
head=(struct list *)malloc(sizeof(struct list));
create(head,n);
printout(head);
locate(head,3,n);
printout(head);
}
运行不对啊,
设有8个关键字序列k={ a1 , a2, a3 , a4 , a5 , a6 , a7 , a8 },使用链表作为存储方式,用顺序查找法在序列中查找key= a2和key=b的数据元素(b不存在于k中),如果查找成功,则返回该元素,并在链表中删除它,如果查找不成功,则在链表结尾处插入它作为新的数据元素。
#include <stdio.h>
struct list
{
int data;
struct list *next;
}*head,*p;
void create (struct list *head,int n) /* 初始化链表,长度为n */
{struct list *p,*s;
int i;
p=head;
printf("\nplease input the elem of linklist:\n");
for(i=1;i<=n;i++)
{s=(struct list *)malloc(sizeof(struct list));
scanf("%d",&s->data);
p->next=s;p=s;s->next=NULL;}
}
void delete (struct list *head,int i)/* 删除链表中第i个结点 */
{struct list *q,*p=NULL;
int k;
q=head;
if(i==1)
head->next=q->next->next;
else
{ p=head;
{for(k=1;k<i;k++)
p=p->next;}
p->next=p->next->next;
}
}
void printout (struct list *head)/* 输出链表中各个结点的数据域 */
{struct list *p;
p=head->next;
printf("\nthe elem of linklist are:\n");
while(p)
{printf("%5d",p->data);
p=p->next;}
printf("\n");
}
int locate(struct list *head,int e,int n)/*查询链表中数据为e的元素*/
{
struct list *p,*s,*q;
int i;
p=head;
while(p&&p->data!=e)
{for(i=1;i<=n;i++)
{p=p->next;
if(p==NULL){ printf("There is not this elem in this linklist!\n") ;
delete(head,i);return(i);
}
else {printf("The elem exits in this linklist!\n");
s=(struct list *)malloc(sizeof(struct list));
s->data=e;s->next=NULL;q=s;p->next=q;return(0);
}
}}}
main()
{struct list *head,*s;int n=8;
head=(struct list *)malloc(sizeof(struct list));
create(head,n);
printout(head);
locate(head,3,n);
printout(head);
}
运行不对啊,