在链表abcde的第3个位置插入f。
#include
#include
struct node
{
char data;
struct node *next;
};
struct node* creat(int n)
{
struct node *head,*tail,*p;
int i;
head=(struct node*)malloc(sizeof(node));
tail=head;
for(i=0;istruct node*)malloc(sizeof(node));
scanf("%c",&p->data);
tail->next=p;
tail=p;
}
tail->next=NULL;
return head;
}
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
printf("\n");
}
void insert(struct node *head,int i,char e)
{
struct node *p,*q;
int j;
p=head;
j=0;
while(p!=NULL&&j-1)
{
p=p->next ;
j++;
}
q=(struct node *)malloc(sizeof(node));
q->data =e;
q->next =p->next ;
p->next =q;
}
int main()
{
struct node * h;
int m,d;
char c;
printf("请输入数据个数:");
scanf("%d",&m);
printf("请输入%d个数据:",m);
h=creat(m);
printf("请输入要插入的数据及位置:");
scanf("%c %d",&c,&d);
insert(h,d,c);
print(h);
return 0;
}
刚学了数据结构,在输入m个数据后程序自动结束,请问哪里出错了,具体怎么修改,谢谢
第17行 64行两句输入语句修改,消除缓冲区残留的字符,供参考:
#include<stdio.h>
#include<stdlib.h>
struct node
{
char data;
struct node *next;
};
struct node* creat(int n)
{
struct node *head,*tail,*p;
int i;
head=(struct node*)malloc(sizeof(node));
tail=head;
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(node));
scanf(" %c",&p->data);//修改
//scanf("%c",&p->data);
tail->next=p;
tail=p;
}
tail->next=NULL;
return head;
}
void print(struct node *head)
{
struct node *p;
p=head->next;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
printf("\n");
}
void insert(struct node *head,int i,char e)
{
struct node *p,*q;
int j;
p=head;
j=0;
while(p!=NULL && j < i-1)
{
p=p->next ;
j++;
}
q=(struct node *)malloc(sizeof(node));
q->data =e;
q->next =p->next ;
p->next =q;
}
int main()
{
struct node * h;
int m,d;
char c;
printf("请输入数据个数:");
scanf("%d",&m);
printf("请输入%d个数据:",m);
h=creat(m);
printf("请输入要插入的数据及位置:");
scanf(" %c %d",&c,&d); //修改
//scanf("%c %d",&c,&d);
insert(h,d,c);
print(h);
return 0;
}