下面通过C++代码实现单链表的如下简单操作
viod Add(T val); //在链表尾部添加元素
bool InsertAt(int pos, T val); //在索引为pos的位置插入元素val
bool Remove(); //删除链表尾部元素
boo RemoveAt(int pos); //删除任意指定索引所在元素
T GetHeadVal(); //返回链表头部元素的值
T GetTailVal(); //尾部元素的值
int Find(T val); //如果找到链表中有此元素返回索引号,没找到返回-1
bool IsEmpty(); //判断链表是否为空
void Clear(); //清空链表
int Size(); //返回链表元素总个数
1.节点类定义
template<class T>
struct Node
{
T val; //结点值
Node<T>* next; //指向下一个元素的指针
Node(T nVal)
{
val = nVal;
next = NULL;
}
Node(void){}
};
2.链表类的定义
#include "Node.h"
#include <iostream>
using namespace std;
template<class T>
class LinkList
{
int size; //元素个数
public:
Node<T>* head; //链表头部指针
Node<T>* tail; //链表尾部指针
LinkList(void) //构造函数
{
head = tail= NULL;
size = 0;
}
~LinkList(void) {Clear();}
void Add(T val) //尾部添加元素
{
Node<T>* pNode = new Node<T>(val);
if(head == NULL) //当链表为空时
{
head = pNode;
tail = pNode;
}
else{
tail->next = pNode;
tail = pNode;
}
size ++;
}
bool InsertAt(int pos,T val) //插入元素
{
Node<T>* pNode = NULL;
if(pos < 0 || pos > size){
cout<<"out of range"<<endl;
return false;
}
if(pos == size) //在尾部插入元素
{
Add(val);
returntrue;
}
elseif(pos == 0) //在头部插入元素
{
pNode = new Node<T>(val);
pNode->next = head;
head = pNode;
}
else{
Node<T>* pNode = GetPointerAt(pos - 1); //返回插入位置前面元素指针
Node<T>* newNode = new Node<T>(val);
newNode->next = pNode->next;
pNode->next = newNode;
}
size ++;
return true;
}
bool Remove(){//删除尾部元素
return RemoveAt(size - 1);
}
bool RemoveAt(int pos) //删除指定位置元素
{
Node<T>* pNode = NULL;
if(size == 0 ){
cout<<"list is empty"<<endl;
returnfalse;
}
if(pos < 0 || pos > size - 1){
cout<<"out of range"<<endl;
returnfalse;
}
if(size == 1) //只有一个元素时相当清空链表
{
Clear();
}
else{
if(pos == 0) //删除头部元素
{
pNode = head;
head = head->next;
delete pNode;
}
else{
Node<T>* pPreNode = GetPointerAt(pos - 1);
pNode = pPreNode->next;
pPreNode->next = pNode->next;
delete pNode;
if(pos == size - 1) //尾部元素
tail = pPreNode;
}
}
size -- ;
return true;
}
T GetHeadVal() {
if(size == 0){
cout<<"list is empty"<<endl;
return NULL;
}
return head->val;
}
T GetTailVal() {
if(size == 0){
cout<<"list is empty"<<endl;
return NULL;
}
return tail->val;
}
int Find(T val) //查找元素
{
int index = 0;
Node<T>* ip = head;
while(ip != NULL){
if(ip->val == val)
return index;
ip = ip->next;
index++;
}
return -1;
}
bool IsEmpty(){return size == 0 ?true:false;}
int Size(){ return size;}
void Clear(){
while(head != NULL){
Node<T>* tmp = head->next;
delete head;
head = tmp;
}
tail = NULL;
size = 0;
}
private:
Node<T>* GetPointerAt(int pos){
Node<T>* pNode = NULL;
if(pos < 0 || pos > size - 1)
cout<<"out of range"<<endl;
else{
pNode = head;
for(int i = 1; i <= pos; i++)
pNode = pNode->next;
}
return pNode;
}
}
;