数据结构-线性表-双向链表
来源:互联网 发布:java 1到100阶乘 编辑:程序博客网 时间:2024/05/17 07:32
贴一个代码
#include <iostream>using namespace std;template<class T>class DsqList{ typedef struct Node { T data; Node *pre; Node *next; }; //结构体 private: Node *first; public : //构造、析构函数 DsqList(); DsqList(T a[],int n); ~DsqList(); //功能函数 //计算链表长度 int Length(); //打印链表 void Print(); //按位查找数据 T GetData(int size); //按值查找 int GetSize(T data); //插入元素 void Insert(T data,int size);};template<class T>DsqList<T>::DsqList() //无参构造{ first = new Node; first->next = NULL; first->pre = NULL;}template<class T>DsqList<T>::DsqList(T a[],int n) //创建链表{ first = new Node; first->next = NULL; first->pre = NULL; Node *p = first; for(int i = 0;i < n;i ++) { Node *newnode = new Node; newnode->data = a[i]; newnode->pre = p; first->pre = newnode; p->next=newnode; newnode->next = first; p = newnode; }}template<class T>DsqList<T>::~DsqList()//析构函数{ Node *p = first->next; while(p != first) { Node *tp = p; p = p->next; first->next = p; p->pre = first; } delete(first);}template<class T>int DsqList<T>::Length() //计算长度{ int len = 0; Node *p = first; while(p->next!=first) { p=p->next; len ++; } return len;}template<class T>void DsqList<T>::Print() //打印链表{ Node *p = first; while(p->next!=first) { p=p->next; cout<<p->data<<" "; } cout<<endl;}template<class T>T DsqList<T>::GetData(int size) //查找某个位置数据{ int i = 0; Node *p = first; while(p->next!=first) { p = p->next; i ++; if(size == i) return p->data; } throw "找不到对应值";}template<class T>int DsqList<T>::GetSize(T data) //查找某个数据位置{ int i = 0; Node *p = first; while(p->next!=first) { p=p->next; i ++; if(p->data == data) return i; } return -1;}template<class T>void DsqList<T>::Insert(T data,int size) //在某个位置插入数据{ int i = 0; Node *p = first; while(p->next!=first) { p = p->next; i ++; if(i == size) { Node *pt = new Node; pt->data = data; //创建节点 Node *pr = p->pre; pt->next = p; pr->next = pt; p->pre = pt; pt->pre = pr; } }}int main(){ float a[] = {1.0,2,3,3.3,4,5.21,6}; DsqList<float> ds(a,7); cout<<"链表长度"<<ds.Length()<<endl; cout<<"打印链表"<<endl; ds.Print(); cout<<"查找元素3.3"<<'\t'<<ds.GetSize(3.3)<<endl; cout<<"查找位置5"<<'\t'<<ds.GetData(5)<<endl; cout<<"在1号位置和7号位置插入元素后:"<<endl; ds.Insert(0,1); ds.Insert(99.99,8); ds.Print(); return 0;}
- 数据结构-线性表-双向链表
- 数据结构----线性表----双向链表
- 数据结构--线性表--双向链表
- 数据结构与算法-----双向线性链表
- 数据结构之线性结构--双向链表
- <数据结构>线性表.循环链表和双向链表
- 数据结构---线性表----循环链表和双向链表
- 数据结构学习笔记(4.线性表之双向链表)
- 数据结构学习笔记(4.线性表之双向链表)
- Java数据结构(四):线性表之双向链表
- Java数据结构-线性表之双向链表
- 数据结构(10)线性表之双向链表
- 数据结构之线性表——双向链表
- 数据结构之线性结构--双向循环链表
- [SDUT](2053)数据结构实验之链表九:双向链表 ---双向链表(线性表)
- 线性表(双向链表)
- 线性表-双向链表
- 数据结构--双向链表
- MB与MQ区别(IBM)
- dynamic_cast介绍
- C/C++语言误区—— void main( )
- Duilib编译成静态库
- undo表空间重建和缩小undo表空间
- 数据结构-线性表-双向链表
- Exchange Server 2010 OWA基于表单身份验证剖析
- Cycling
- 指针的学习
- 在字符串中查找连续重复的最长子串的C++实现
- 古人两个通病:懒和穷
- c语言详解sizeof & sizeof函数总结
- hdu 4283
- 如何使用打成jar文件