当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++基础入门教程

C++版--链表

#include "head.h"
#include "iostream.h"
#include "string.h"

typedef char ElemType;

typedef struct LNode{
  ElemType data;
  struct LNode *next;
}LNode,*Link;

class LinkList
{
private:
 Link head;
public:
 LinkList(){}
 LinkList(ElemType a[]);
 void CreateLinkList();
 void inver();
 ElemType get(int i);
 Status insert(int loc,ElemType e);
 ElemType del(int i);
 void print();
 void MergeList(LinkList la,LinkList lb);
};
LinkList::LinkList(ElemType a[])
{
  int n=strlen(a),i;
  Link p;
  head=new LNode;
  head->next=NULL;
  for(i=n-1;i>=0;i--)
  {
    p=new LNode;
 p->data=a[i];
 p->next=head->next;
 head->next=p;
  }
};
void LinkList::print()
{
  Link p=head->next;
 while(p)
 {
   cout<<p->data<<"->";
   p=p->next;
 }
 cout<<"NULL"<<endl;
};
void LinkList::CreateLinkList()
{
  int n;
  cout<<"请输入你要构建的表的长度:";
  cin>>n;
  ElemType *e;
  e=new ElemType[n];
  cin>>e;
  int i;
  Link p;
  head=new LNode;
  head->next=NULL;
  for(i=n-1;i>=0;i--)
  {
    p=new LNode;
 p->data=e[i];
 p->next=head->next;
 head->next=p;
  }
 
}
ElemType LinkList::get(int i)
{
  int cnt=1;
  Link p=head->next;
  while(cnt!=i)
   p=p->next;
  return p->data;

}
Status LinkList::insert(int loc,ElemType e)
{
  Link p=head;
  int j=0;
  while(p&&j++<loc-1) p=p->next;
  if(!p||j>loc-1) return ERROR;
  Link s=new LNode;
  s->data=e;
  s->next=p->next;
  p->next=s;
  return OK;
}

相关内容
赞助商链接