/*
链表类的一些功能:
(1)向链表中插入元素,主要包括向链表头插入元素和向链表尾插入元素
(2)从链表中删去元素,主要包括删去链表头元素和删去链表尾元素
(3)所有结点的删除
为了实现上述功能,同时为了满足面向对象程序设计的要求,一般需要两个类来对链表进行管理:
一个类是link,它主要用来管理链表中每个结点中的数据以及指向下一个结点的指针;
另一个类是list,它主要用来对链表进行管理并提供对链表的操作。
下面将给出满足上述要求的链表设计程序。
*/
#include<iostream>
using namespace std;
#include<string.h>
class link
{
friend class list;
link *next;
char str[20];
public:
link(){
strcpy(str,"\0");
}
link(const char *s){
strcpy(str,s);
}
link *get(){
return(next);
}
void disp(){
cout<<str<<endl;
}
};
class list
{
link *first;
link *last;
public:
list(){
first=last=new link;
}
~list(){
quanshan();
delete first;
}
list &toucha(const link &x);
list &weicha(const link &x);
list &toushan();
list &weishan();
list &quanshan();
void disp();
};
list &list::toucha(const link &x)
{
link *p=first;
first=new link;
*first=x;
first->next=p;
return(*this);
}
list &list::weicha(const link &x)
{
link *p=last;
*p=x;
last=new link;
p->next=last;
return(*this);
}
list &list::toushan()
{
if(first==last);
else
{
link *p=first->next;
delete first;
first=p;
}
return(*this);
}
list &list::weishan()
{
if(first==last);
else if(first->next==last)
{
toushan();
}
else
{
link *p=first;
link *s;
while(p->next!=last)
{
s=p;
p=p->next;
}
s->next=last;
delete p;
}
return(*this);
}
list &list::quanshan()
{
link *p=first;
while(p!=last)
{
link *s;
s=p->next;
delete p;
p=s;
}
first=last;
return(*this);
}
void list::disp()
{
link *p=first;
int n=1;
while(p!=last)
{
cout<<n<<":";
p->disp();
n++;
p=p->next;
}
}
int main()
{
list dt;
dt.weicha(link("wang"));
dt.weicha(link("zhang"));
dt.toucha(link("zao"));
dt.weicha(link("meng"));
dt.disp();
return 0;
}
设计中碰到的问题:
1、最开始给link初始化的时候,代码如下:
class link
{
friend class list;
char str[20];
link *next;
public:
link(){
strcpy(str,"\0");
}
link(char *s){
strcpy(str,s);
}
……
};
这时候编译器会出现warning
原因是
char * 背后的意思是给我个字符串,我要修改它
而理论上我们传给函数的字面常量是无法被修改的
const char * 背后的意思是给我个字符串,我要读取它
这样写更加合理
具体参考如下连接,非常详细:
warning:deprecated conversion from string constant to 'char *'解决方案