实验二单链表
来源:互联网 发布:网络摄像机管理软件 编辑:程序博客网 时间:2024/04/29 20:02
#include<iostream>using namespace std;template<class T>struct Node{ T data;Node<T>*next;};template<class T>class Linklist{public:Linklist();Linklist(T a[],int n);~Linklist();void Insert(int i,T x);int Locate(T x);T Delete(int i);void Printlist();private:Node<T>*first;};template<class T>Linklist<T>::Linklist(){first=new Node<T>;first->next=NULL;}template<class T>Linklist<T>::Linklist(T a[],int n){Node<T> *r,*s;first=new Node<T>;r=first;for(int i=0;i<n;i++){s = new Node<T>; s->data=a[i]; r->next =s; r=s; } r->next= NULL; } template<class T>Linklist<T>::~Linklist(){Node<T> *q = NULL; while(first != NULL) { q = first; first= first->next; delete q; } } template<class T>void Linklist<T>::Insert(int i,T x){Node<T>*p=first,*s=NULL;int count = 0; while(p!=NULL&&count< i-1) { p = p->next; count++; } if(p==NULL) throw "位置非法"; else { s = new Node<T>; s->data =x; s->next=p->next; p->next= s; } } template<class T>T Linklist<T>::Delete(int i){Node<T> *p =first,*q=NULL; T x; int 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; return x; } } template<class T>int Linklist<T>::Locate(T x){ Node<T>*p =first->next; int count =1; while(p!=NULL) { if(p->data==x) return count; p=p->next; count++; } return 0; } template<class T>void Linklist<T>::Printlist(){ Node<T>*p =first-> next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } void main(){ int a[3] = {4, 5, 6}; Linklist<int> B(a, 3); cout << "插入前的数据为:" << endl; B.Printlist(); B.Insert(2,9); cout << "插入操作后的数据为:" << endl; B.Printlist(); cout << "值为9的元素的位置为:"; cout << B.Locate(9) << endl; cout << "删除前的数据为:" << endl; B.Printlist(); B.Delete(1); cout << "删除后的数据为:" << endl; B.Printlist(); }
0 0
- 实验二单链表
- 实验二单链表
- 实验二单链表
- 实验二单链表
- 实验二单链表的实现
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验
- 实验。。
- 实验
- 实验
- jquery ui js文件的导入顺序
- OpenCV中矩阵数据的访问(二)(Learning OpenCV第三章3)
- 11gR203RAConAix Install
- discuz ajaxpost函数解析
- uClinux 在 S3C4510B 嵌入式开发板上的移植和开发详解
- 实验二单链表
- nginx---支持thinkphp url重写
- 积累的力量
- 从2014年D2前端技术论坛看前端发展趋势
- SDUT 1266-出栈序列的统计(DFS)
- SharePoint 2013: The "New Web Application" button is disabled is the central administration
- Python学习报告
- 整数序列中的众数和中位数
- opencv中遍历图像(Mat格式)