您的位置:首页 > 理论基础 > 数据结构算法

数据结构自学之路---单链表

2016-06-06 00:24 183 查看
#include <iostream>
using namespace std;
template<typename T> class Node;
//单链表的定义
template<typename T> class List
{
private:
Node<T> *head;
public:
List(){
head=new Node<T>();
}
~List(){
delete head;
}
bool insert(int i,T data);   //插入元素
T getnodedata(int i);        //获取指定元素
void clean();               //清除链表
int getlength();            //获取链表长度
bool deletenode(Node<T> *p);   //删除指定链表内容
};
//链表结点的定义
template<typename T> class Node
{
private:
Node<T> *next;
T data;
public:
Node(){
next=NULL;
}
Node(T item,Node<T> *newnext=0){
next=newnext;
data=item;
}
~Node(){
next=NULL;
}
T getdata(){
return data;
}

friend class List<T>;
};
//插入元素的实现
template<typename T> bool List<T>::insert(int i,T data){
Node<T> *p=head;
int j;
for (j=1;j<=i-1;j++)
{
p=p->next;
if (p==NULL)
{
break;
}
}
if (p==NULL&&j<i-1)
{
return false;
}else{
Node<T> *node=new Node<T>(data);
node->next=p->next;
p->next=node;
return true;
}
}
//获取指定下标的数据的实现
template<typename T> T List<T>::getnodedata(int i){
Node<T> *p=head->next;
int j;
for (j=1;j<=i-1;j++)
{
p=p->next;
}
return p->getdata();
}
//获取链表的长度
template<typename T> int List<T>::getlength(){
int counter=0;
Node<T> *p=head->next;
while (p!=NULL)
{
p=p->next;
counter++;
}
return counter;
}
//删除指定的链表元素
template<typename T> bool List<T>::deletenode(Node<T> *p){
Node<T> *node=head;
if (p==NULL)
{
return false;
}else{
while (node->next!=p)
{
node=node->next;
}
node->next=p->next;
delete p;
return true;
}
}
//清除链表的元素
template<typename T> void List<T>::clean(){
Node<T> *p=NULL;
while (p->next!=NULL)
{
p=head->next;
head->next=p->next;
delete p;
}
}

void main()
{
List<int> list;
for (int i=0;i<10;i++)
{
list.insert(i,i*10);
cout<<list.getnodedata(i)<<" ";
}
cout<<endl;
cout<<list.getlength()<<endl;
list.clean();
cout<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: