主要问题在链表插入那一块;具体代码如下
//链表
#include<stdio.h>
#include<stdlib.h>
struct Data{
int num;
struct Data *next;
};
int icount;//记录链表的长度
//创建链表
struct Data *create()
{
struct Data *head,*tail,*pn;
icount=0;
pn=head=(struct Data *)malloc(sizeof(struct Data));
head->next=NULL;
tail=head;
while(1)
{
pn=(struct Data *)malloc(sizeof(struct Data));
printf("please input a num:");
scanf("%d",&pn->num);
if(pn->num==-1)
{
free(pn);//释放内存
pn=NULL;
break;//退出while循环
}
tail->next=pn;
tail=pn;
icount++;
}
tail->next=NULL;
return head;
}
//插入链表
struct Data *insert(struct Data *head)
{
int i;
struct Data *pn,*temp,*f;//f上一个
//pn要插入的新节点
pn=(struct Data *)malloc(sizeof(struct Data));
printf("please input a num :");
scanf("%d",&pn->num);
//第一种情况只有头节点存在
temp=head;
if(head==NULL)
{
head=pn;
pn->next=NULL;
}
//在链表 中插入
else
{
//找到要插入的位置
while((pn->num>temp->num)&&(temp->next!=NULL))
{
f=temp;
temp=temp->next;
}
if(pn->num<=temp->num)
{
if(head==temp)//在表头
head=pn;
else
//表中间
{
f->next=pn;
pn->next=temp;
}
}
//表尾
else
{
temp->next=pn;
pn->next=NULL;
}
}
return head;
}
//删除节点
void Delete(struct Data *head,int num)
{
struct Data *temp,*del;
int i;
temp=head;
del=temp;//del和temp同时指向一个位置
for(i=0;i<num;i++)//使得del指向要删除的节点
{
temp=del;
del=del->next;
}
temp->next=del->next;
free(del);
}
//打印链表
void print(struct Data *head)
{
printf("-----------共有%d个节点-----------\n",icount);
while(head!=NULL)
{
printf("num:%d\n",head->num);
head=head->next;
}
}
int main()
{
int num;
struct Data *head;
head=create();
print(head);
printf("请输入要删除的节点");
scanf("%d",&num) ;
Delete(head,num);
print(head);
printf("请插入节点");
head=insert(head);
printf("插入节点后 :");
print(head);
return 0;
}
错误如下: