C++实现数据结构一 顺序表
2013-04-09 19:16
453 查看
const int Default= 100; template<typename Type> class SeqList { private: Type *m_elements; const int m_maxsize; int m_currentsize; public: //构造函数 SeqList(int size = Default): m_maxsize(size), m_currentsize(0) { if(size > 0) m_elements = new Type[m_maxsize]; } //析构函数 ~SeqList() { delete [] m_elements; } int Length() const { return m_currentsize; } int Find(Type x) const; int IsElement(Type x) const; int Insert(Type x, int i); int Remove(Type x); int IsEmpty() { return m_currentsize ==0 ; } int IsFull() { return m_currentsize == m_maxsize; } Type Get( int i ); void Print(); }; /* 函数功能:查找指定元素在顺序表的位置 函数参数:Type 类型的 x 函数返回值:返回该元素的位置,未找到则返回 0 */ template<typename Type> int SeqList<Type>::Find(Type x) const { int i; for(i=0; i<m_currentsize; i++) { if(x == m_elements[i]) { cout<<"find the element: "<<x<<endl; return i+1; break; } } if(i == m_currentsize) { cout<<"cannot find the element: "<<x<<endl; return 0; } } /* 函数功能:判断指定元素是否在顺序表中 函数参数:Type 类型的x; 函数返回值:在顺序表中返回1,否则返回0; */ template<typename Type> int SeqList<Type>::IsElement(Type x) const { int i =Find(x); if( i == 0) { cout<<x<<" is not in the list"<<endl; return 0; } else return 1; } /* 函数功能:在顺序表指定的位置插入指定的元素 函数参数:Type类型的x, int类型的i 函数返回值:插入成功返回1, 否则返回0; */ template<typename Type> int SeqList<Type>::Insert(Type x, int i) { if(i<1 || i>m_currentsize+1 || m_currentsize == m_maxsize) { cout<<"cannot insert the element "<<endl; return 0; } m_currentsize++; for(int j = m_currentsize-1; j>i-1;j--) m_elements[j]= m_elements[j-1]; m_elements[i-1]= x; return 1; } /* 函数功能:移除顺序表中的指定元素 函数参数:Type类型的x 函数返回值:移除成功返回1,否则返回0 */ template<typename Type> int SeqList<Type>::Remove(Type x) { int i = Find(x); if(i == 0) { cout<<"can not remove the element"<<endl; return 0; } for(int j= i-1; j<m_currentsize-1; j++) m_elements[j] = m_elements[j+1]; m_currentsize--; return 1; } /* 函数功能:获取顺序表中指定位置的元素的值; 函数参数:int 类型的变量i 函数返回值:返回i位置处的元素之,失败则返回0; */ template<typename Type> Type SeqList<Type>::Get(int i) { if(i<1 || i> m_currentsize) { cout<<"cannot get the element"<<endl; return 0; } return m_elements[i-1]; } /* 函数功能:输出顺序表的所有元素 函数参数:无 函数返回值:无 */ template<typename Type> void SeqList<Type>::Print() { for(int i=0; i<m_currentsize; i++) cout<<m_elements[i]<<"\t"; cout<<endl; }
相关文章推荐
- c++实现数据结构1.顺序表
- 数据结构--用C++实现顺序表
- 【源代码】C++实现严蔚敏数据结构所有算法(一)线性表-顺序表
- 常见数据结构的C++实现(一)——顺序表SqList
- 数据结构 顺序表(c++实现)
- C++数据结构: 顺序表 详细实现
- 算法与数据结构课程中的c++实现的顺序表和链表
- 数据结构(1)顺序表 c++ 模板实现
- 数据结构的基础-单向链表所构造的栈 c++实现
- 简单数据结构之 vector 栈(C++ vector 实现)
- 算法与数据结构基础 -- 排序 (C++实现)
- 算法与数据结构基础6:C++队列的简单实现
- C/C++基本数据结构:有序二叉树的基本概念和实现
- 数据结构 带头结点的单链表 操作大全 最全的链表操作(c++实现)
- 【数据结构】用C++实现单链表的各种操作(包括头删,尾删,插入,逆序,摧毁,清空等等)
- 数据结构学习之堆栈的链式存储C++实现
- 几种简单的数据结构的C++实现,树,图,链表,环形队列,栈等---环形队列篇
- 简单数据结构----链栈的C++实现
- 【算法和数据结构】线性表(一)线性表(C++实现)
- c++实现数据结构中的各种排序方法:直接插入、选择,归并、冒泡、快速、堆排序、shell排序