数据结构单链表

来源:互联网 发布:caffe官方文档中文pdf 编辑:程序博客网 时间:2024/05/03 18:31

#include<iostream.h>
struct Node
{
 int data;
 Node *next;
};
class Student{
public:Student();
    Student(int a[],int n);
    void Length();
    void Get(int i);
    void Locate(int x);
    void Insert(int i,int x);
    int Delete(int i);
    void Print();
private:   Node *first,*s,*r;
};
Student::Student()
{
 first=new Node;
 first->next=NULL;
}
Student::Student(int a[],int n)
{
 first=new Node;
 r=new Node;
 r=first;
for(int i=0;i<n;i++)
{
 s=new Node;
 s->data=a[i];
 r->next=s;
 r=s;
}
r->next=NULL;
}
void Student::Length()
{
 int count=0;
 s=first->next;
 if(s!=NULL)
 {
  s=s->next;
     count++;
 }
 cout<<"单链表的长度为:"<<count<<endl;
}
void Student::Get(int i)
{
 s=new Node;
 s=first->next;int count=1;
 while(s!=NULL&&i>count)
 {s=s->next;
 count++;}
 cout<<"元素序号为"<<i<<"的数据为:"<<s->data<<endl;
}
void Student::Locate(int x)
{
 s=new Node;
 int i=1;
 s=first->next;
 while(s!=NULL)
 {
 if(x==s->data) cout<<"查找值为"<<x<<"的元素序号为:"<<i<<endl;
  i++;
  s=s->next;
 }
 
}
void Student::Insert(int i,int x)
{
 r=first;int count=0;
 while(r!=NULL&&count<i-1)
 {
 r=r->next;
 count++;
 }
 if(r==NULL)throw'位置';
  else{
 s=new Node;
 s->data=x;
 s->next=r->next;
 r->next=s;}
}
int Student::Delete(int i)
{
 r=first;int count=0;int x;
 while(r!=NULL&&count<i-1)
 {r=r->next;
 count++;
 }
 if(r==NULL||r->next==NULL)throw'异常';
 else{s=new Node;
 s=r->next;
  x=s->data;
 r->next=s->next;
 delete s;
 return x;
}}
void Student::Print()
{
 r=first->next;
 cout<<"学生的成绩为:";
 while(r!=NULL)
 {
 cout<<r->data<<" ";
 r=r->next;
 }
}
void main()
{
 int a[10]={10,9,8,7,6,5,4,3,2,1};
 Student s1(a,10);
 s1.Length();
 s1.Get(3);
 s1.Locate(8);
 s1.Insert(3,8);
 s1.Delete(3);
 s1.Print();
}


 

0 0