#include <iostream>
using namespace std;
class Node{
public:
float data;
Node *next;
Node(float i = 0,Node *p = NULL):data(i),next(p) { }
};
class Linklist{
Node *head;
int num;
public:
Linklist();
void Makelist(float *a,int n);//创建链表
void Print();//遍历链表
void Add(int l,float d);//增加数据
bool Delete(int l);//删除某一个节点
bool Change(int l,int d);//改变某一结点
~Linklist();
};
//实现函数部分
Linklist::Linklist()
{
head = new Node();
num = 0;
}
void Linklist::Makelist(float *a,int n)
{
num = n;
Node *p = head;
for(int i = 0;i < n;i++)
{
Node *s = new Node(a[i]);
p ->next = s;
p = s;
}
}
void Linklist::Print()
{
Node *p = head;
while(p!=NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
void Linklist::Add(int l,float d)
{
Node *p = head;
int i;
for(i = 1;i < l;i++)
p = p->next;
Node *s = new Node(d);
s->next = p->next;
p ->next = s;
}
bool Linklist::Delete(int l)
{
if(l>num)
{
cout<<"out of boundary"<<endl;
return false;
}
Node *p = head;
Node *q = head;
if(l == 1)
{
head = head ->next;
delete p;
}
else
{
for(int i = 2;i<l;i++)
{
p = p->next;
}
for(int i = 1;i<l;i++)
{
q = q->next;
}
p->next = q->next;
delete q;
}
return true;
}
bool Linklist::Change(int l,int d)
{
if(l>num)
{
cout<<"out of boundary"<<endl;
return false;
}
Node * p = head;
for(int i = 1;i < l;i++)
{
p = p->next;
}
p ->data = d;
return true;
}
Linklist::~Linklist()
{
Node *p =head;
while(head!= NULL)
{
head = head->next;
delete p;
p = head;
}
}
//void Makelist(float *a,int n);//创建链表
// void Print();//遍历链表
// void Add(int l,float d);//增加数据
// bool Delete(int l);//删除某一个节点
// bool Change(int l,int d);//改变某一结点
//测试部分
int main()
{
float a[5] = {1,2,3,4,5};
Linklist l;
l.Makelist(a,5);
l.Print();
l.Add(1,10);
l.Print();
l.Delete(3);
l.Print() ;
l.Change(3,5);
l.Print() ;
return 0;
}
C++实例-链表的简单操作
最新推荐文章于 2023-06-14 20:41:55 发布