数据结构之单链表(C++)

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值