实验2循环双链表

实验目的:掌握双链表的基本知识与运用

实验内容:运用尾插法实现双链表的插入数据,并实现双链表查找、删除等功能


#include<iostream>

using namespace std;

template<class T>

struct Node

{

T data;

Node<T> *next,*prior;

};

template<class T>

class Student{

public:

Student();

Student(T a[],int n);

~Student();

T Get(int i);

int locate(T x);

void Insert(int i,T x);

T Delete(int i);

void foreach();

private:

Node<T> *first;

};

//无参构造函数

template<class T>

Student<T>::Student(){

first=new Node<T>;

first->next=NULL;

first->prior=NULL;

}

//尾插法建表

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;

s->prior=r;

r=s;

}

r->next=first;

first->prior=r;

}

//析构函数

template<class T>

Student<T>::~Student(){

    Node<T> *p=first->next;  

    Node<T> *t;  

    t=first;  

    while(p!=first)  

    {  

      delete t;  

      t=p;  

      p=p->next;

    }

}

//按位查找

template<class T>

T Student<T>::Get(int i){

Node<T>*p=first->next;

int l=1;

while(p!=first&&l<i){

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 *p=first;  

    Node *s;  

    int count=0;  

    while(p!=NULL&&count<i-1)  

    {  

      p=p->next;  

      count++;  

    }  

    if(p==NULL) throw "没有找到结点";  

    else  

    {  

      s=new Node;  

      s->data=x;  

      s->prior=p;  

      s->next=p->next;   

      p->next->prior=s;  

      p->next=s;  

    }  

}

//删除

template<class T>

T Student<T>::Delete(int i){

Node<T>*p,*q;

p=first->next;

int l=0;

while(p!=NULL&&l<i-1){

p=p->next;

l++;

}

if(p==NULL||p->next==NULL) throw "位置";

else {

q=p->next;T x=q->data;

p->next=q->next;

delete q;

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,70};

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;

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值