C++ 单链表模板类实现

 

  • 单链表的C语言描述

  • 基本运算的算法——置空表、求表的长度、取结点、定位运算、插入运算、删除运算、建立不带头结点的单链表(头插入法建表)、建立带头结点的单链表(尾插入法建表),输出带头结点的单链表

 

#include<cstdio>
#include<iostream>
using namespace std;
template <class T>
class Linklist
{
private:
struct node
{
T date;
node * next;
node():next(NULL) {}
node(T d):date(d),next(NULL) {}
};
node* head;
node* tail;
node* cur;
int len;
public:
Linklist();
node* getNode()
{
return cur;
}
void setValue(T d)
{
node *tmp = new node(d);
tail->next = tmp;
tail = tmp;
len++;
}
T getValue()
{
T ret = cur->next->date;
cur = cur->next;
return ret;
}
bool hasNext()
{
if(cur->next == NULL)
{
cur = head;
return false;
}
return true;
}
int getLength()
{
return len;
}
bool Insert(Linklist<T> & dusk,int i,T e)
{
int j = 1;
node * p = new node(e);
tail = cur;
while(tail && j<i)
{
tail= tail ->next;
j++;
}
if(!tail||j>i)return false;
p->next = tail ->next;
tail->next = p;
len++;
return true;
}
bool Delete(Linklist <T> & dusk,int i)
{
int j = 1;
tail = cur;
while(tail&&j<i)
{
tail = tail -> next;
j++;
}
if(!tail || j>i)return false;
node * p = new node();
p= tail ->next;
tail->next = p->next;
delete(p);
return true;
}

 

bool Destroy(Linklist<T> & dusk)
{
node * p = new node();
if(head == NULL)
return true;
while(head)
{
p = head ->next;
delete(head);
head = p;
}
}
};

 

template <class T>
Linklist<T>::Linklist()
{
head = new node();
tail = head;
cur = head;
head -> next = NULL;
len = 0;
}

 

int main()
{
int a,b=99;
Linklist<int>dusk;
for(int i = 0; i < 10; i ++)
{
dusk.setValue(i);
}
while(dusk.hasNext())
{
cout<<dusk.getValue()<<" ";
}
cout<<endl;
while(dusk.hasNext())
{
cout<<dusk.getValue()<<" ";
}

 

}

 

 

 

 

 

 

 

 

 

 

建立不带头结点的单链表(头插入法建表)

 

#include<iostream>
using namespace std;
template <class T>
class Sqlist
{
private:
struct node{
T data;
node * next;
node():next(NULL){};
node(T d):data(d),next(NULL){};
};
public:
Sqlist(T d);
void setValue(T d)
{
node * tem = new node(d);
tem -> next =head;
head = tem;
len++;
}
T getValue()
{
T ret = cur->data;
cur = cur -> next;
return ret;

 

}
int len;
node * head;
node * cur;
};
template <class T>
Sqlist<T>::Sqlist(T d)
{
node * head = new node(d);
cur = head;
};
int main()
{
int a = 1;
Sqlist<int> dusk(a);
for(int i = 0 ; i < 5 ; i++)
dusk.setValue(i);
dusk.cur = dusk.head;
for(int i = 0 ; i< 5 ; i++)
{
cout<<dusk.getValue();
}

 

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C++ 单链表模板类实现,布布扣,bubuko.com

C++ 单链表模板类实现

上一篇:JavaScript网站设计实践(七)编写最后一个页面 改进表单


下一篇:什么是http返回状态码