头文件:
#include <iostream>
#include <cstring>
using namespace std;
struct Node
{
int data;
Node *next;
};
class CCircleList
{
public:
CCircleList(); //创建一个头结点,next 指向自己
virtual ~CCircleList();
void CreateCircleList(int a[], int n); //有参析构函数,建立只有头结点的空链表
int Length(); //求单链表的长度
int Get(int i); //按位查找,在单链表中查找第I个结点的元素值
int Locate(int x); //按值查找,在单链表中查找值x的元素序号
void Insert(int n, int x); //插入操作,在第I个位置插入元素值为x的结点
void Delete(int n); //删除查找,在单链表中删除第I个结点
void Modify(int i, int x); //修改操作,修改第I个
void PrintList(); //遍历操作,按序号依次输出元素
private:
Node *first; //单链表的头指针
int length; //长度
};
cpp文件
#include "CircleList.h"
#include <iomanip>
#include <iostream>
using namespace std;
//初始化,头节点指向自己
CCircleList::CCircleList()
{
first = new Node;
first->next = first;
first->data = 0;
length = 0;
}
CCircleList::~CCircleList()
{
delete(first);
}
//创建单链表的循环链表
void CCircleList::CreateCircleList(int a[], int n)
{
if(n<0)
{
cout << "你输入的长度不正确 " << endl;
}
else
{
length = n;
Node *p,*q;
p = first;
while(n--)
{
q = new Node;
q->data = a[n];
p->next = q;
q->next = first;
p = q;
}
}
}
//打印链表的值
//时间复杂度O(n)
void CCircleList::PrintList()
{
Node *p;
p = first->next;
while(p!=first)
{
cout<<setw(2)<<p->data;
p=p->next;
}
}
//链表长度
int CCircleList::Length()
{
return length;
}
//按序号查找
//平均时间性能为O(N),为顺序存取结构
int CCircleList::Get(int i)
{
Node *p;
p = first->next; //工作指针初始化
int count = 1;
while(p!= first && count < i)
{
p = p->next; //工作指针后移,不能p++
count++;
}
if (p == NULL) throw "位置错误";
else return p->data;
}
//按值查找
int CCircleList::Locate(int x)
{
Node *p;
p = first->next; //工作指针初始化
int count = 1;
while(p!= first)
{
if (p->data == x) return count; //查找成功,结束并返回序号
p = p->next; //工作指针后移,不能p++
count++;
}
return 0; //退出循环表明查找失败
}
//插入操作
//找到要插入位置的前一个位置
//把前一个位置的next 给 新结点的next
//把前一个位置的next 指向新结点
void CCircleList::Insert(int n, int x)
{
Node *q,*p = new Node();
p->data = x;
q = first;
for(int i = 1;i<n;i++)
q = q->next;
p->next = q->next;
q->next = p;
}
//删除操作
void CCircleList::Delete(int n)
{
if(n<0||n>length)
{
cout<<"删除的位置是错误的";
return;
}
else
{
Node *p,*q;
p = first;
for(int i=1;i<n;i++)
p=p->next;
q = p->next;
p->next = q->next;
delete q;
q = NULL;
length--;
}
}
测试代码:
#include <iostream>
using namespace std;
#include "CircleList.h"
int main()
{
CCircleList list;
int a[7] = {1, 2, 3, 4, 5, 6, 7};
int n, data;
cout<<"测试数据为:"<<endl;
for (int i = 0; i < 7; i++)
cout<<a[i];
list.CreateCircleList(a, 7);
cout<<"打印循环单链表"<<endl;
list.PrintList();
cout << "请选择你要删除的结点位置:";
cin >> n;
list.Delete(n);
cout << "删除后的单链表:";
list.PrintList();
cout << "请输入你要插入的下标和值:";
cin >> n >> data;
list.Insert(n , data);
list.PrintList();
cout << "请输入你要查询的下标:";
cin >> n;
data = list.Get(n);
cout<< "该位置的值为:"<<data;
cout << "请输入你要查询的值:";
cin >> n;
data = list.Locate(n);
cout<< "该值的位置为:"<<data;
return 0;
}