纯属无聊,自己实现了一下双向链表,主要操作有头插法尾插法建表,从前往后和从后往前遍历,其他的功能暂时没有实现,因为只是无聊,但是唯一的收获就是:真的理解了头结点(尾节点)的重要性和便捷性,最初是从大话数据结构得知的这个问题,不明觉厉,所以自己动手,果然发现,只有头指针真的会有很多不方便,其中奥秘,各位慢慢体会。
以下是我的实现,只有头指针,没有头结点:
#include<memory>
#include<iostream>
#include<string>
using namespace std;
class doublelinknode
{
public:
int data;
doublelinknode* next;
doublelinknode * front;
doublelinknode(){ front=next = nullptr; }
};
class doublelinklist
{
public:
doublelinknode *head,*reap;//只存放头尾指针,不存放数据,无头结点
int count;
doublelinklist(){ count = 0; head=reap = nullptr; }
void headinsert(int e);
void reapinsert(int e);
void popfront(int& e);
void popback(int& e);
};
void doublelinklist::headinsert(int e)
{
doublelinknode *temp = new doublelinknode();
temp->data = e;
if (count == 0)//因为没有头结点和尾节点,所以第一个节点要区分开
{
reap = temp;
head = temp;
}
else
{
temp->next = head;
head->front = temp;
head = temp;
}
count++;
}
void doublelinklist::reapinsert(int e)
{
doublelinknode *temp = new doublelinknode();
temp->data = e;
if (count==0)
{
head = temp;
reap = temp;
}
else
{
temp->front = reap->front;
reap->next = temp;
reap = temp;
}
count++;
}
void doublelinklist::popfront(int& e)
{
if (count==0)
{
return;
}
if (count==1)
{
reap = nullptr;
}
e = head->data;
count--;
doublelinknode *tem = head;
head = head->next;
if (head)
{
head->front = nullptr;
}
delete tem;
}
void doublelinklist::popback(int& e)
{
if (count == 0)
{
return;
}
if (count==1)
{
head = nullptr;
}
e = reap->data;
count--;
doublelinknode *tem = reap;
reap = reap->front;
if (reap)
{
reap->next = nullptr;
}
delete tem;
}
int main()
{
int a;
doublelinklist lys1,lys2;
cin >> a;
while (a)
{
lys1.reapinsert(a);//尾插法建表
lys2.headinsert(a);//头插法建表
cin >> a;
}
cout <<"size1:"<< lys1.count << endl;
cout << "size2:" << lys2.count << endl;
while (lys1.count)
{
lys1.popfront(a);//从头遍历
cout << a;
cout << " current size1:"<<lys1.count << endl;
}
while (lys2.count)
{
lys2.popback(a);//从尾遍历
cout << a;
cout << " current size2:" << lys2.count << endl;
}
return 0;
}
输入 0 截止。