| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 368 人关注过本帖
标题:添加错误!!
只看楼主 加入收藏
tobyliying
Rank: 1
等 级:新手上路
帖 子:49
专家分:0
注 册:2007-4-16
收藏
 问题点数:0 回复次数:1 
添加错误!!

// classlinklist.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream.h"

struct student
{
int num;
char name[20];
student *next;
};
class linklist
{
private:
int n;
student *head;
public:
linklist();
~linklist();
void creat();
void add();
void del();
void show();
};
linklist::linklist(){}
linklist::~linklist()
{
student*p1,*p2;
p1=p2=head;
while(n>=0)
{
p2=p1;
p1=p1->next;
delete p2;
n--;
}
}
void linklist::creat()
{
student*p1,*p2;
head=NULL;
n=0;
p2=p1=new student;
cout<<" input num and name:" <<endl;
cin>>p1->num>>p1->name ;
while(p1->num!=0)
{
n++;
if(n==1)
head=p1;
else
p2=p1;
p1=new student;
cout<<" input num and name:" <<endl;
cin>>p1->num>>p1->name ;
p2->next=p1;
}
p1->next=NULL;

}
void linklist::add()
{
student*p1,*p2;
int k,m;

while(k<4)
{
cout<<"please choose: top=1 , mid=2, last=3, exit=4"<<endl;
cin>>k;
p1=p2=head;
if(k==1)
{
p1=new student;
cout<<"input num and name"<<endl;
cin>>p1->num>>p1->name ;
head=p1;
p1->next=p2;
n++;
}
else if(k==2)
{
cout<<"please choose address:"<<endl;
cin>>m;
while(p1->next!=NULL&&m!=0)
{
p2=p1;
p1=p1->next;
m--;
}
if(m==0)
{
p2=new student;
cout<<"input num and name"<<endl;
cin>>p2->num>>p2->name ;
p2->next=p1->next;
p1->next=p2;
n++;
}
else
cout<<"not been found"<<endl;
}
else if(k==3) //当在末尾添加成功后退出。会出错是为什么。
{
while(p1->next!=NULL)
{
p2=p1;
p1=p1->next;
}
p1=new student;
cout<<"input num and name"<<endl;
cin>>p1->num>>p1->name ;
p1->next=NULL;
p2->next =p1;
n++;
}
}
}
void linklist::del()
{
student*p1,*p2;
int i;
p1=p2=head;
cout<<"will delete num(exit=0):"<<endl;
while(i!=0)
{
cin>>i;
if(i==1)
{
head=p1->next;
delete p2;
n-- ;
}
else if(i-1<=n)
{
while(i>1&&p1->next!=NULL)
{
p2=p1;
p1=p1->next;
i--;
}
if(i==1)
{
p2->next=p1->next;
delete p1;
n--;
}
else cout<<"not been found";

}
}
}
void linklist::show()
{
student*p1, *p2;
p1=p2=head;
while(p1->next!=NULL)
{
p2=p1;
cout<<"num: "<<p2->num<<"\t name: "<<p2->name<<endl;
p1=p1->next;
}
cout<<"num: "<<p1->num<<"\t name: "<<p1->name<<endl;
}

int main(int argc, char* argv[])
{
linklist user;
int inti;
user.creat();
while(inti!=4)
{
cout<<"add=1, delete=2, show=3, exit=4" <<endl;
cin>>inti;
if(inti==1)
user.add();
else if(inti==2)
user.del();
else if(inti==3)
user.show();
}
return 0;
}

2007-06-26 00:35
smartwind
Rank: 1
等 级:新手上路
威 望:1
帖 子:277
专家分:0
注 册:2006-11-13
收藏
得分:0 
循环结束时,加上p2=p1;

2007-06-26 10:37
快速回复:添加错误!!
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.011141 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved