#ifndef LIST_H
#define LIST_H
/************************************************************************/
/* C++实现单链表
/************************************************************************/
#include <iostream>
using namespace std;//这里为什么会出现NULL没有定义?
typedef char Elemplent;
//结点类定义
class Node
{
public:
Node* next;
Elemplent data;
Node();
Node(Node* temptr = NULL,Elemplent temdata=' ');
};
//结点默认构造函数
Node::Node()
{
next = NULL;
}
//创建新节点的构造函数
Node::Node(Node* temptr,Elemplent temdata)
{
next = temptr;
data = temdata;
}
//链表类定义
class List
{
protected:
Node* head ;
Node* temp;
public:
void init();
List();
~List();
public:
bool insertHeader(const Elemplent& elempent = ' ');
bool insertTail(const Elemplent& elempent = ' ');
int GetCount();
Node* locateWithLocation(int position = 1) const;
Node* locateWithElemplent(const Elemplent& elempent = ' ')const;
bool Insert(const int position = 1,const Elemplent& elempent = ' ');
bool Delete(const int position = 1);
bool Clear();
};
//构造函数
List::List()
{
init();
}
//析构函数及释放工作
List::~List()
{
Clear();
delete head;
}
void List::init()
{
head = new Node();
temp =head;
}
//得到结点数
int List::GetCount()
{
int i =0;
while(temp->next!=NULL)
i++;
return i;
}
//在头插入元素
bool List::insertHeader(const Elemplent& elempent /* = "" */)
{
Node* newnode = new Node(head->next,elempent);
head->next = newnode;
return true;//存在bug
}
//在末尾插入元素
bool List::insertTail(const Elemplent& elempent /* = ' ' */)
{
Node* temp = locateWithLocation(GetCount());
Node* newnode = new Node(NULL,elempent);
temp->next = newnode;
return true;
}
//得到指针用position
Node* List::locateWithLocation(int position /* = 1 */)const
{
int j=1;
Node* temp;
while(temp!=NULL&&j<position)
{
j++;
temp = temp->next;
}
return temp;
}
//得到指针用elemplent
Node* List::locateWithElemplent(const Elemplent& elempent /* = ' ' */)const
{
Node* temp;
while(temp!=NULL && elempent == temp->data)
{
temp = temp->next;
}
return temp;
}
//在一个位置插入一个元素
bool List::Insert(const int position /* = 1 */,const Elemplent& elempent /* = ' ' */)
{
Node* temp = locateWithLocation(position);
if(temp ==NULL)
{
return false;
}
Node* newnode =new Node(temp->next,elempent);
temp->next = newnode;
return true;
}
//删除一个元素用位置;
bool List::Delete(const int position /* = 1 */)
{
Node* temp = locateWithLocation(position-1);
if (temp ==NULL||temp->next==NULL)
{
return false;
}
Node* delatenode = temp->next;
temp->next =delatenode->next;
delete delatenode;
return true;
}
//删除所有元素
bool List::Clear()
{
while (GetCount()==0)
{
Delete(1);
}
}
#endif
数据结构之单链表(C++)
最新推荐文章于 2023-03-07 17:17:38 发布