尝试写一篇博客2(链表面向对象)
由C转C++面向对象
//通过面向对象的方式来实现。
//首先,先用C语言的方式进行链表的所有操作。但是发现其中没有长度的限制;也没有具体对象的linklist,只有一个head(当然,这种情况也可以用结构体来解决);
//所以,制造了一个类,类中间包括了所有链表需要进行的操作(函数),当然也有了长度的限制,有了其中的头,这就有了面向对象的概念;
//但是,即使是有了这些东西,参数也得需要设置,学到的方法有两种1,设置set get的public类型的函数设置 2,构造函数进行设置,本程序就是利用的第二种方法;
//由此,之前每个函数需要传递head的指针变成了这个linklist固有的head,所以调用其中的时候不再传递head了,这就是面向对象的优点所在
struct Lnode
{
int value;
Lnode *next;
};
class Linklist
{
public:
Linklist();
Linklist(int length, Lnode *head) {
this->length = length;
this->head = head;
};
~Linklist();
bool CreateLinklist(int length, int * source);
void ShowMessage();
bool Insert(int i, int key);
bool Delete(int i);
private:
int length;
Lnode *head = new Lnode();
};
Linklist::Linklist()
{
}
Linklist::~Linklist()
{
}
bool Linklist::CreateLinklist(int length, int * source) {
for (auto i = 0; i < length; i++)
{
//头插法建立
Lnode *p = new Lnode();
p->value = source[i];
p->next = head->next;
head->next = p;
}
return 1;
}
void Linklist::ShowMessage() {
Lnode *p = head->next;
while (p != NULL)
{
cout << p->value << endl;
p = p->next;
}
}
bool Linklist::Insert(int i,int key) {
int j = 0;
Lnode *p = head;
while (j++ < i-1) {
p = p->next;
}
Lnode *q = new Lnode();
q->value = key;
q->next = p->next;
p->next = q;
return 1;
}
bool Linklist::Delete(int i) {
auto j = 0;
Lnode *p = head;
while (j++ < i - 1) {
p = p->next;
}
Lnode *q = p->next;
p->next = q->next;
q->next = NULL;
delete q;
return 1;
}
int main() {
Lnode *head = new Lnode();
Linklist s(10,head);
int a[] = { 10,9,8,7,6,5,4,3,2,1 };
if (sizeof(a) / 4 > 10)
return -1;
s.CreateLinklist(10, a);
s.ShowMessage();
s.Insert(5, 12);
cout << "after inserting" << endl;
s.ShowMessage();
s.Delete(5);
cout << "after deleting" << endl;
s.ShowMessage();
return 0;
}