我发现这个链表建的有问题。那个rear指针指的是第100个结点,当第十个结点为表尾(非真正表尾)而插入样例中的第11个结点时,其实是将此节点插到了第101的位置……所以输出时“表尾”数据不是真正表尾数据。
样例输入:
10
2001 M
2002 F
2003 M
2004 F
2005 M
2006 F
2007 M
2008 F
2009 M
2010 F
1
10
2011 F
本想写个双向的链表,不小心写成了单向的。
其中插入部分还有错~~
#include<cstdio>
#include<cstdlib>
using namespace std;
int n;
struct ddl{
int info;
char sex;
struct ddl *next;
}stu;
struct ddl *head,*rear;
void build_ddl(){
struct ddl *p1=NULL,*p2;
int i=0;
for(i=0;i<100;i++){
p1=(struct ddl *)malloc(sizeof(struct ddl));
if(!p1){printf("dynamic ditribution of memo failed!\n");break;}
if(!i)head=p1;
if(i)p2->next=p1;
p2=p1;
}
rear=p2;
rear->next=NULL;
}
void output_(){
struct ddl *p=head;
int i;
for(i=1;i<=n;i++){
printf("number %d students' info: %d %c\n",i,p->info,p->sex);
p=p->next;
}
}
void input(){
int i;
struct ddl *p=head;
printf("input number of students,students' info: ID and sex:\n");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d %c",&p->info,&p->sex);
p=p->next;
}
output_();//这里报错:expected constructor,destructor,or type conversion before';'token
}
void insert_afteri_pos(){//插入表尾时出错!!
int i;
struct ddl *p=NULL;
printf("(insert)please input the position(i<=n),info and sex:\n");
scanf("%d",&i);
if(i<0||i>n){
printf("invlalid input!please input again:\n");
insert_afteri_pos();
}
else{
p=(struct ddl *)malloc(sizeof(struct ddl));
if(!p){
printf("insert data failed!\n");
return ;
}
if(!i){
p->next=head;
head=p;
}
else if(i<n){
struct ddl *p1=head;
for(int j=1;j<i;j++) p1=p1->next;
p->next=p1->next;
p1->next=p;
}
else{
rear->next=p;
p->next=NULL;
rear=p;
}
scanf("%d",&p->info);
getchar();
scanf("%c",&p->sex);
n++;
output_();
}
}
void delete_y(){
int i;
struct ddl *p=head;
printf("(delete)please input the ID of student:\n");
scanf("%d",&i);
while(p->info!=i)p=p->next;
if(!p)printf("no such student!");
else{
if(p==head){
head=head->next;
free(p);
}
else if(p==rear){
p=head;
while(p->next!=rear)p=p->next;
p->next=NULL;
free(rear);
rear=p;
}
else{
struct ddl *p1=head;
while(p1->next!=p)p1=p1->next;
p1->next=p->next;
free(p);
}
}
n--;
output_();
}
void free_ddl(){
free(head);
}
int main(){
int t;
build_ddl();
input();
while(1){
printf("please input your choices:\n");
printf("1.insert a student.\n");
printf("2.delete a studnt.\n");
printf("3.exit.\n");
scanf("%d",&t);
switch(t){
case 1:insert_afteri_pos();break;
case 2:delete_y();break;
case 3:free_ddl();return 0;
default :printf("input error!please input validly:\n");break;
}
}
}