//1.添加功能找到并删除一个学生数据,
//2.有序的维护链表
#include<iostream>
#include<cstring>
using namespace std;
class CPerson
{
friend class CNode;
public:
CPerson(){}
CPerson(char*name,int age,char*str=0,char sex='M')
{
strncpy(this->str,str,9);
strncpy(this->name,name,20);
this->age=age;
this->sex=sex;
}
CPerson(CPerson &one)
{
strncpy(this->str,one.str,9);
strncpy(this->name,one.name,20);
this->age=one.age; this->sex=one.sex;
}
char*GetName()
{ return name; }
char*GetNo()
{ return str;}
/*char* del()
{
CNode::Del();
}*/
void Show() //在一行中显示信息
{
cout<<"姓名"<<name<<",学号:"<<str<<",性别"<<(sex=='M'?"男":"女")<<",年龄"<<age<<endl;
}
private:
char name[20];
char str[9];
char sex;
int age;
};
class CNode
{
friend class CSimpList;
friend class CPerson;
public:
CPerson GetData()
{ return data; }
CNode* GetNext()
{ return next; }
CNode* Del(CNode *p)
{
CNode *head;
head=NULL;
p=NULL;
if(p==head)
{
head=p->next;
}
else
{
front->next=p->next;
free(p);
cout<<"该结点已成功删除!"<<endl;
}
return head;
}
private:
CPerson data; //数据域
CNode *next; //指针域
CNode *front;
};
class CSimpList
{
public:
CSimpList()
:pHead(NULL),pCur(NULL)
{}
~CSimpList()
{
CNode*p=pHead;
while(pHead)
{
pHead=p->next;
delete p;
p=pHead;
}
}
void SetCurToHead()
{ pCur=pHead; }
void ShowCurData()
{ pCur->data.Show(); }
void operator +=(CPerson &one) //重载链表的结点“+=”操作
{
CNode*b=new CNode;
b->data=one;
//添加到链表中
CNode*p=pHead;
if(NULL==p)
{
pHead=b; b->next=NULL; //将b作为第一个结点
pCur=pHead;
}else
{
//找到链表最后一个结点
while(p->next!=NULL) p=p->next;
p->next=b;
b->next=NULL; //符合添加情况(2)
}
}
CNode*operator[](char*str) //重载链表的[]操作
{
CNode *p=pHead;
while(p)
{
if(strcmp(p->data.GetNo(),str)==0) return p;
p=p->next;
}
return NULL;
}
friend CNode*operator++(CSimpList&one,int); //后缀++运算符友元重载声明
private:
CNode *pHead;
CNode *pCur;
};
CNode*operator++(CSimpList&one,int)
{
if(NULL!=one.pCur->GetNext())
{
one.pCur=one.pCur->GetNext();
return one.pCur;
}else
return NULL;
}
int main()
{
CSimpList list;
CPerson one("WANG",27,"19120123",'W');
list+=one;
one=CPerson("DING",38,"19120124",'M');
list+=one;
one=CPerson("ZHANG",33,"19120125",'M');
list+=one;
CNode*find=list["19120123"];
if(find)
{
find->GetData().Show();
find->Del(find);
}
else
{
cout<<"没有找到!"<<endl;
}
find=list["19120128"];
if(find)
{
find->GetData().Show();
find->Del(find);
}
else
{
cout<<"没有找到!"<<endl;
}
//遍历
list.SetCurToHead();
list.ShowCurData();
while(list++)
list.ShowCurData();
return 0;
}