运行环境:CodeBlocks
本程序使用模板类创建链表,并实现添加数据,删除数据,反转链表,连接两链表功能。
主程序 main.cpp
//Written by Xuebi
//本程序使用模板类创建链表,并实现添加数据,删除数据,反转链表,连接两链表功能
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List<int> st;
st.Insert(10);
st.Insert(20);
st.Insert(30);
st.Insert(40);
st.show();//40->30->20->10
st.Invert();
st.show();//10->20->30->40
List<int> st1;
st1.Insert(50);
st1.Insert(60);
st1.Insert(70);
st1.Insert(80);
st1.show();//80->70->60->50
st1.show();//50->60->70->80
st.Connect(st1);
st.show();//10->20->30->40->50->60->70->80
st.Delete(60);
st.show();//10->20->30->40->50->70->80
return 0;
}
头文件 List.h
#ifndef LIST_H
#define LIST_H
#include <iostream>
template<class T> class List;//声明List,方便ListNode声明为友元函数
template<class T>
class ListNode//链表节点
{
friend class List<T>;//声明为链表的友元函数,List可以访问ListNode的私有成员 反思:声明友元函数friend class List会报错
private:
T data;//数据域
ListNode*p;//ListNode类型指针
ListNode(T element);//构造函数
};
template<class T>
class List
{
private:
ListNode<T>*first;//List私有成员只有链表的头部
public:
List();
void Insert(T element);
void Delete(T element);
void Invert();
void show();
void Connect(List<T> L);
};
template<class T>
List<T>::List()//初始化链表时,为空链表
{
first=0;
}
template<class T>
ListNode<T>::ListNode(T element)
{
data=element;
p=0;
}
template<class T>
void List<T>::Insert(T element)
{
ListNode<T>*A=new ListNode<T>(element);//动态创建一个ListNode类型指针A
A->p=first;//A指向的ListNode类里面的指针指向first,first目前仍是空指针
first=A;//现在first重新指向开头
}
template<class T>
void List<T>::show()
{
ListNode<T>*A;
A=first;
if(!first)
{
std::cout<<"This chaine is void!,cannot show()! "<<std::endl;
}
else
{
for(A;A;A=A->p)
{
std::cout<<A->data;
if(A->p)
{
std::cout<<" -> ";
}
}
std::cout<<std::endl;
}
}
template<class T>
void List<T>::Delete(T element)
{
if(!first)
{
std::cout<<"This chaine is void!,cannot Delete()! "<<std::endl;
}
else
{
ListNode<T>*current=first;
ListNode<T>*previous=0;
for(current;current&&((current->data)!=element);previous=current,current=current->p)
{
;
}
if(current)
{
if(previous)
{
previous->p=current->p;
}
else
{
first=first->p;
}
delete current;
}
}
}
template <class T>
void List<T>::Invert()//链表真是艺术!!!!本函数用于倒转链表
{
ListNode<T>*A=first;//A指针用于向下搜索
first=0;
while(A)
{
ListNode<T>*FIRST=first;
ListNode<T>*B=A;//B用来暂时记录A
A=A->p;
B->p=FIRST;
first=B;
}
}
template <class T>
void List<T>::Connect(List<T> L)//连接两链表
{
if(!first)//如果本链表为空,则L链表直接接在first后面
{
first=L.first;
}
else
{
ListNode<T>*A=first;
for(A;A->p;A=A->p)//本链表非空,向下搜索,查找最后的ListNode
{
;
}
A->p=L.first;
}
}
#endif // LIST_H
本程序仅供学习参考之用,如若转载,请注明出处。
如果你对本程序感到满意,可点击关注本博客!!