#include <iostream>
#include <string>
using namespace std;
class DoublyLinkList
{
private:
typedef struct _Node{
string name;
_Node *pre;
_Node *next;
_Node():name("None"), pre(NULL),next(NULL){};//_Node结构的构造函数
_Node(string input):name(input), pre(NULL),next(NULL){};//另外一个构造函数
}Node;
Node *head;
Node *tail;
int size;
public:
DoublyLinkList();
~DoublyLinkList(); //使用了new DoublyLinkList(), 需要自定义析构函数
void addToHead(string);//从head开始加入节点
void show();//从head开始遍历打印
void showRev(); //从tail开始遍历打印
Node* find(int);//返回第x个节点的指针
Node* findHead();
Node* findTail();
int findSize();//返回节点数目
friend ostream& operator << (ostream&, const Node&);//重载<<运算符
};
ostream& operator << (ostream &os, const DoublyLinkList::Node& node)
{
return os << "Name: " << node.name;
}
DoublyLinkList::DoublyLinkList()
{
head = NULL;
tail = NULL;
size = 0;
}
int DoublyLinkList::findSize()
{
return size;
}
DoublyLinkList::~DoublyLinkList()
{
Node *p, *q ;
for (p = head; p; p = q)
{
q = p->next;
cout << "now deleting: " << *p << endl;
delete p;
}
}
void DoublyLinkList::addToHead(string name)
{
Node *pNode = new Node(name);
if (size == 0)
{
head = pNode;
tail = pNode;
}
else
{
head->pre = pNode;
pNode->next = head;
head = pNode;
}
size++;
}
void DoublyLinkList::show()
{
Node *pHead = head;
while(pHead != NULL)
{
cout << *pHead << endl;
pHead = pHead->next;
}
}
void DoublyLinkList::showRev()
{
Node *pTail = tail;
while(pTail != NULL)
{
cout << *pTail << endl;
pTail = pTail->pre;
}
}
//此处注意写法:不能只写 Node* DoublyLinkList::fing(int num)
DoublyLinkList::Node* DoublyLinkList::find(int num)
{
int start = 1;
Node* pHead = head;
while (start != num){
start++ ;
pHead = pHead->next;
}
return pHead;
}
DoublyLinkList::Node* DoublyLinkList::findHead()
{
return head;
}
DoublyLinkList::Node* DoublyLinkList::findTail()
{
return tail;
}
int main()
{
DoublyLinkList *dll = new DoublyLinkList();
cout << "Please input the names in the doubly link list(q to quit): " << endl;
string name = "NULL";
while(1)
{
cin >> name;
if (name != "q")
dll->addToHead(name);
else
break;
}
cout << "the size of the DoublyLinkList is: "<< dll->findSize()<< endl;
dll->show();
cout<<endl;
dll->showRev();
cout<<endl;
for (int i = 1; i <= dll->findSize(); i++)
{
cout<<"the "<<i<<"th element is:";
cout<<*(dll->find(i))<<endl;
}
cout<<"head is: ";
cout<<*(dll->findHead())<<endl;
cout<<"tail is: ";
cout<<*(dll->findTail())<<endl;
delete dll;
return 0;
}
//到底是用struct还是用class来定义Node比较好呢?
//c++的struct和class一样,可以定义构造函数;
//struct和class的区别:
//C++支持的结构体,这种结构类事实上和类class功能相同,但有一点区别
// 区别在于<span style="font-family: Arial, Helvetica, sans-serif;">类中默认的访问控制级别为 private</span>
// 结构体中默认的访问控制级别为 public