现在的位置: 首页 > 综合 > 正文

链表的实现

2013年08月22日 ⁄ 综合 ⁄ 共 1799字 ⁄ 字号 评论关闭

#include<iostream>
using namespace std;
template<class T>
class LinkList
{
 struct Node
{
 T data;
 Node * next;
};
 Node * head;
 public:
  LinkList(T a[],int n=0)
  {
   head=new Node;
   head->next=0;
   head->data=0;
   for(int i=0;i<n;i++)
   {
    Node * x=new Node;
    x->data=a[i];
    x->next=head->next;
    head->next=x;
   }
  }//利用尾插法来构建线性链表
  ~LinkList()
  {
   while(head!=NULL)
   {
    Node * y=head->next;
    head->next=y->next;
    delete y;
   }
  }
  bool IsEmpty()//不为空,则返回0,为空则返回非0
  {
   return (head==NULL);
  }
  T GetNode(int i)
  {
   if(i<0)
   {
    cout<<"i值错误!!"<<endl;
    exit(0);
   }
   Node * x=head;
   int j=0;
   while(j<=i)
   {
    x=x->next;
    j++;
   }
   return x->data;
  }
  int Length()
  {
   int i=0;
   Node * x=head;
   while(x!=NULL)
   {
    x=x->next;
    i++;
   }
   return i-1;
  }
  int LocateNode(T x)
  {
   int i=0;
   Node * y=head;
   while((y->data)!=x)
   {
     i++;
     y=y->next;
   }
   return i+1;
   
  }
  void Insert(int i,T x)
  {
   if(i<0)
   {
    cout<<"i值错误!"<<endl;
    exit(0);
   }
   Node * y=head;
   int j=0;
   while(j<i)
   {
    y=y->next;
    j++;
   }
   Node * z=new Node;
   z->data=x;
   z->next=y->next;
   y->next=z;
  }
  void Delete(int i)
  {
   if(i<0)
   {
    cout<<"i值错误!"<<endl;
    exit(0);
   }
   int j=0;
   Node * x=head;
   while(j<i-1)
   {
    j++;
    x=x->next;
   }
   Node * k=x->next;
   x->next=k->next;
   delete k;
  }
  void show()
  {
   Node * x=head;
   while(x!=NULL)
   {
    cout<<x->data<<",";
    x=x->next;
   }
   cout<<endl;
  }
};
int main()
{
 int a[10]={1,2,3,4,5,6,7,8,9,10};
 LinkList<int> str(a,10);
 str.show();
 cout<<"此线性表是空的吗?"<<endl;
 switch(str.IsEmpty())
 {
 case 0:cout<<"NO"<<endl;cout<<"此表的长度为:"<<str.Length()<<endl;break;
 case 1:cout<<"YES"<<endl;
 }
 int x=str.GetNode(3);
 cout<<x<<"为线性表中的第"<<str.LocateNode(x)<<"个元素!!"<<endl;
 str.show();
 str.Insert(3,x);
 cout<<"插入后:"<<endl;
 str.show();
 str.Delete(3);
 cout<<"删除后:"<<endl;
 str.show();
 return 1;
}

抱歉!评论已关闭.