单链表

来源:互联网 发布:软件模块接口参数 编辑:程序博客网 时间:2024/06/04 23:32

1.实验目的

使用单链表,用于实践


2.实验代码

头文件

#include <iostream>
class Node
{
public:
 float data;
 Node  *next;
 Node(){
  next=NULL;}
};

class List{
public:
 List(){first=new Node;first->next=NULL;}
 List(float a[],int n);
 int length();
 void Get(int i);
 void insert(int i,float x);
 float Delete(int i);
 void printList();
private:
 Node *first;
 int count;
};

源文件:

#include <iostream>
#include "tou.h"
using namespace std;

void List::printList()
{
 Node *p;
 p=first->next;
 while(p!=NULL)
 {
  cout<<p->data<<",";
  p=p->next;
 }
}


int List::length(){
 Node *p;
 p=first->next;
 count=0;
 while(p!=NULL)
 {
  p=p->next;
  count++;
 }
 return count;}

void List::Get(int i){
 Node *p;
 p=first->next; count=1;
 while(p!=NULL&&count<i)
 {
  p=p->next;
  count++;
 }
 if(p==NULL)throw"位置";
 else cout<<endl<<"The price is:"<<p->data<<endl;
}

void List::insert(int i,float x){
 Node *p; Node *s=new Node();
 p=first; count=0;
 while(p!=NULL&&count<i-1)
 {
  p=p->next;
  count++;
 }
 if(p==NULL) throw"位置";
 else{
     s->data=x;
  s->next=p->next; p->next=s;
  cout<<endl;
 }
}

List ::List(float a[],int n){
 first=new Node;
 Node *s,*r;
 r=first;
 for(int i=0;i<n;i++){
  s=new Node; s->data=a[i];
  r->next=s;
  r=s;
}
 r->next=NULL;
}

float List::Delete(int i){
 Node *p,*q;
 float x;
 p=first; count=0;
 while(p!=NULL&&count<i-1)
 {
  p=p->next;
  count++;
 }
 if(p==NULL||p->next==NULL)
  throw"位置";
 else{
  q=p->next; x=q->data;
  p->next=q->next;
  delete q;
  return x;
 }
}

void main(){
 int n; int i;
 float a[]={99,11,22,33,44};
 n=5;
    List x(a,n);
 x.printList();
 x.Get(2);
 x.Delete(2);
 x.printList();
 x.insert(2,11);
 x.printList();
 system("pause");
}


3.实验心得:

虽然明白了单链表原理,但实施起来并不容易,需要多多实践。





原创粉丝点击