数据结构 链表类定义代码.doc_第1页
数据结构 链表类定义代码.doc_第2页
数据结构 链表类定义代码.doc_第3页
数据结构 链表类定义代码.doc_第4页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

链表类定义:将该类保存在文件LinkList.h中。/链表类定义:将该类保存在文件LinkList.h中。template struct NodeT data;Node *next; /此处也可以省略;template class LinkListpublic:LinkList( )first=new Node; first-next=NULL; /建立只有头结点的空链表LinkList(T a , int n); /建立有n个元素的单链表LinkList( ); /析构函数int Length( ); /求单链表的长度T Get(int i); /取单链表中第i个结点的元素值int Locate(T x); /求单链表中值为x的元素序号void Insert(int i, T x); /在单链表中第i个位置插入元素值为x的结点T Delete(int i); /在单链表中删除第i个结点void PrintList( ); /遍历单链表,按序号依次输出各元素private:Node *first; /单链表的头指针;template LinkList: LinkList( )Node * p=first; /工作指针p初始化while (p) /释放单链表的每一个结点的存储空间Node * q=p; /暂存被释放结点p=p-next; /工作指针p指向被释放结点的下一个结点,使单链表不断开delete q; template T LinkList:Get(int i) Node *p; int j; p=first-next; j=1; /或p=first; j=0; while (p & jnext; /工作指针p后移 j+; if (!p) throw 位置; else return p-data;template void LinkList:Insert(int i, T x) Node *p; int j; p=first ; j=0; /工作指针p初始化 while (p & jnext; /工作指针p后移 j+; if (!p) throw 位置; else Node *s; s=new Node; s-data=x; /向内存申请一个结点s,其数据域为x s-next=p-next; /将结点s插入到结点p之后 p-next=s;template T LinkList:Delete(int i) Node *p; int j; p=first ; j=0; /工作指针p初始化 while (p & jnext; j+; if (!p | !p-next) throw 位置; /结点p不存在或结点p的后继结点不存在 else Node *q; int x; q=p-next; x=q-data; /暂存被删结点 p-next=q-next; /摘链 delete q; return x;template LinkList: LinkList(T a , int n)first=new Node;first-next=NULL; /初始化一个空链表for (int i=0; in; i+) Node * s=new Node;s-data=ai; /为每个数组元素建立一个结点s-next=first-next; /插入到头结点之后first-next=s;template void LinkList:PrintList( )Node *p;p=first-next;while (p) coutdatanext;#include #includeLinkList.hvoid main( ) int r =10,9,8,7,6,5,4,3,2,1; LinkList a( r , 10 ); cout原表为:endl; a.PrintList(); coutendl; a.Insert(1,-2); /执行插入操作; a.Insert(2,-1); a.Insert(3,0 ); cout执行插入后输出为:endl; a.PrintList(); coutendl; a.Delete(0); a.Delete(-1); a.Delete(-2); cout执行删除后输出为:endl; a.PrintL

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论