实验2循环链表

来源:互联网 发布:五金进销存软件 编辑:程序博客网 时间:2024/06/04 00:38

目的:通过实际操作循环链表,掌握循环链表的链式储存结构以及验证单链表及其操作的实现并进一步理解算法与程序的关系。

 

内容:用尾插法建立带头结点的单链表并对已创建的循环链表实现插入、删除、查找等基本操作。



#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class Student{
public:
Student();
Student(T a[],int n);
~Student();
int Length();
T Get(int i);
int locate(T x);
void Insert(int i,T x);
T Delete(int i);
void foreach();
private:
Node<T> *first;
int length;
};
//无参构造函数
template<class T>
Student<T>::Student(){
first=new Node<T>;
first->next=first;
}
//尾插法建表
template<class T>
Student<T>::Student(T a[],int n){
first=new Node<T>;
Node<T> *s,*r;
r=first;
for(int i=0;i<n;i++){
s=new Node<T>;s->data=a[i];
r->next=s;
r=s;
length++;
}
r->next=first;
}
//析构函数
template<class T>
Student<T>::~Student(){
Node<T>*q=first;
for(int i=0;i<length;i++){
q=first;
first=first->next;
delete q;
}
cout<<"链表已经成功删除"<<endl;
}
//按位查找
template<class T>
T Student<T>::Get(int i){
Node<T>*p;
p=first->next;
int l=0;
while(p!=first&&l<i-1){
p=p->next;
i++;
}
if(p==first)throw "位置";
else return p->data;
}
//按值查找
template<class T>
int Student<T>::locate(T x){
Node<T> *p;
p=first->next;
int l=1;
while(p!=first){
if(p->data==x)return l;
p=p->next;
l++;
}
return 0;
}
//插入
template<class T>
void Student<T>::Insert(int i,T x){
Node<T>*p=NULL;
p=first->next;
Node<T> *s;
int l=1;
while(p!=first&&l<i-2){
p=p->next;
l++;
}
if(p==NULL) throw "位置";
else {
s=new Node<T>;
s->data=x;
s->next=p->next;
p->next=s;
length++;
}
}
//删除
template<class T>
T Student<T>::Delete(int i){
Node<T>*p,*q;
p=first->next;
int l=0;
while(p!=first&&l<i-2){
p=p->next;
l++;
}
if(p==first||p->next==NULL) throw "位置";
else {
q=p->next;T x=q->data;
p->next=q->next;
delete q;
length--;
return x;
}
}
//遍历
template<class T>
void Student<T>::foreach(){
Node<T>*p;
p=first->next;
while(p!=first){
cout<<p->data<<",";
p=p->next;
}
}
void main(){
int a[]={80,90,70,50,100};
int num=5;
Student<int> stu(a,num);
stu.foreach();
cout<<"查找90分同学所在位置"<<stu.locate(90)<<endl;
// cout<<"查找第三个同学分数"<<stu.Get(3)<<endl;
// cout<<"在第3个和第4个学生之间插入成绩60"<<endl;
// stu.Insert(60,4);
cout<<"查找60分学生位置"<<stu.locate(60)<<endl;
cout<<"删除第三个成绩"<<stu.Delete(3)<<endl;

}

运行结果:

原创粉丝点击