64,649
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<malloc.h>
typedef struct Student
{
int num;
struct Student *next;
}student;
/**************创建链表******************/
student * creat(int temp)
{
student *L,*p,*h;
h=L=(student*)malloc(sizeof(student));
h->next=NULL;
while((p->num)!=temp)
{
p=(student*)malloc(sizeof(student));
scanf("%d",&p->num);
L->next=p;
L=p;
}
L->next=NULL;
return h;
}
/**********输出链表********************/
void output(student *head)
{
student *p;
p=head->next;
while(p!=NULL)
{
printf("%3d",p->num);
p=p->next;
}
}
/******定位元素,返回该地址**************/
student *LocateElem(student *head,int elem)
{
student *p;
p=head->next;
while(p!=NULL && p->num!=elem)
{
p=p->next;
}
return p;
}
/******返回前驱************************/
student *PriorElem(student *L,int elem)
{
student *p,*q;
p=L->next;
while(p!=NULL && p->num != elem)
{
q=p;
p=p->next;
}
return q;
}
/***************求表长****************/
int Lenth(student *L)
{
int n=0;
while(L->next!=NULL)
{
n++;
L=L->next;
}
return n;
}
/*************插入元素****************/
int ListInsert(student *L,int i,int elem)
{
int n;
student *s,*p;
p=L->next;
s=(student *)malloc(sizeof(student));
s->num=elem;
/* if(i<1 || i>Lenth(L)+1)
{
printf("您输入超出范围");
return 0;
} */
for(n=1;n<i;n++)
{
p=p->next;
}
s->next=p->next;
p->next=s;
return 1;
}
/*******************删去元素**********************/
int Delete(student *L,int i)
{
int j;
student *p=L,*q;
if(i<1 || i>Lenth(L))
{
printf("您输入有误");
return 0;
}
while(j<i)
{
p=p->next;
j++;
}
q=p->next;
p->next=q->next;
free(q);
return 1;
}
int main()
{
student *head;
int x,elem,Len;
int insert_i,e;
printf("请输入链表最后一个值作为结束标志:");
scanf("%d",&x);
printf("请输入链表元素:\n");
head=creat(x);
printf("输出所有结点");
output(head);
Len=Lenth(head);
printf("\n链表长:%d",Len);
printf("\n请输入插入的元素:");
scanf("%d",insert_i);
printf("请输入插入的位置:");
scanf("%d",e);
ListInsert(head,e,elem);
output(head);
/*printf("从链表中一个元素输出到最后,那么请输入这个元素:");
scanf("%d",elem);
output(LocateElem(head,elem)); */
return 0;
}
/**************创建链表******************/
student * creat(int temp)
{
student *L,*p,*h;
h=L=(student*)malloc(sizeof(student));
h->next=NULL;
////////////////////--Kulv--2010/11/18---20:58:45--///////////////////////
int newNum = 0 ;
scanf("%d",&newNum);
while( newNum != temp )//这里原来的严重错误
{
p=(student*)malloc(sizeof(student));
p->num = newNum ;
L->next=p;
L=p;
scanf("%d", &newNum);
}
L->next=NULL;
return h;
}
int ListInsert(student * &L,int i,int elem),
函数声明跟定义都改成如上