循环单链表(代码完整)头⽂件:
#include <iostream>
#include <cstring>
using namespace std;
struct Node
{
int data;
Node *next;
};
class CCircleList
{
cstring转为int
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;
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;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。