c++实现链表;
说明:在C语言实现链表的基础上,用c++实现;
自己感觉不是太完美,还是有c语言的影子,后期又改进成摸板类实现。
参见:c++实现链表2
源码:list.h ; list.cpp ; main.cpp
#ifndef __LIST_H
#define __LIST_H
#include <iostream>
using namespace std;
typedef char EleType;
class ChainNode
{
public:
ChainNode();
ChainNode(EleType data);
ChainNode *GetNext();
void SetNext(ChainNode *next);
EleType GetData();
private:
EleType m_data;
ChainNode *m_next;
};
class List
{
public:
List();
~List();
List(const List &l); //拷贝构造函数
List &operator=(const List &l); //拷贝赋值运算符
bool Append(EleType data);
bool Insert(int pos, EleType data);
bool Delete(int pos);
void Clear();
bool Traverse(int (* visit)(EleType data));
ChainNode *GetAddr(int pos);
private:
ChainNode *m_head;
ChainNode *m_tail;
};
#endif // __LIST_H
#include "list.h"
ChainNode::ChainNode()
{
m_data = 0;
m_next = nullptr;
}
ChainNode::ChainNode(EleType data)
{
m_data = data;
m_next = nullptr;
}
void ChainNode::SetNext(ChainNode *next)
{
m_next = next;
}
ChainNode *ChainNode::GetNext()
{
return m_next;
}
EleType ChainNode::GetData()
{
return m_data;
}
List::List()
{
m_head = new ChainNode();
m_tail = m_head;
}
List::~List()
{
delete m_head;
}
List::List(const List &l)
{
m_head = new ChainNode(*l.m_head);
}
List &List::operator=(const List &l)
{
ChainNode *newp = new ChainNode(*l.m_head);
delete m_head;
m_head = newp;
return *this;
}
bool List::Append(EleType data)
{
ChainNode *newp = new ChainNode(data);
m_tail->SetNext(newp);
m_tail = newp;
return true;
}
bool List::Delete(int pos)
{
ChainNode *pre = GetAddr(pos - 1);
if((pre != nullptr) && (pre->GetNext() != nullptr))
{
ChainNode *p = pre->GetNext();
pre->SetNext(p->GetNext());
if(m_tail == p)
{
m_tail = pre;
}
delete p;
return true;
}else
{
return false;
}
}
ChainNode *List::GetAddr(int pos)
{
int n = 0;
ChainNode *p = m_head;
if(pos < 0)
{
return nullptr;
}
while((p != nullptr) && n < pos)
{
p = p->GetNext();
n++;
}
return p;
}
void List::Clear()
{
while(Delete(1));
}
bool List::Insert(int pos, EleType data)
{
ChainNode *newp = new ChainNode(data);
ChainNode *pre = GetAddr(pos - 1);
if(pre == nullptr)
{
return false;
}
newp->SetNext(pre->GetNext());
pre->SetNext(newp);
if(newp->GetNext() == nullptr)
{
m_tail = newp;
}
return true;
}
bool List::Traverse(int (* visit)(EleType data))
{
ChainNode *p = m_head->GetNext();
while(p != nullptr)
{
if(!visit(p->GetData()))
{
return false;
}
p = p->GetNext();
}
return true;
}
#include "list.h"
int visit(EleType data);
int main()
{
List *lp = new List();
lp->Append('a');
lp->Append('b');
lp->Append('c');
lp->Insert(4, 'd');
lp->Append('e');
lp->Delete(5);
lp->Append('h');
lp->Clear();
lp->Traverse(visit);
return 0;
}
int visit(EleType data)
{
cout << data << endl;
return 1;
}