数据结构实验-用C++实现带头结点的循环链表

来源:互联网 发布:长沙知豆电动车租赁 编辑:程序博客网 时间:2024/06/05 20:33

用C++实现带头结点的循环链表.直接上代码,如下


File chainNode.h#ifndef chainNode_#define chainNode_template <class T>struct chainNode{   // data members   T element;   chainNode<T> *next;   // methods   chainNode() {next=NULL;}   chainNode(const T& element)      {   this->element = element;   this->next=NULL;      }   chainNode(const T& element, chainNode<T>* next)      {this->element = element;       this->next = next;}};#endifFile linnerList.h// abstract class linearList// abstract data type specification for linear list data structure// all methods are pure virtual functions#ifndef linearList_#define linearList_#include <iostream>using namespace std;template<class T>class linearList{   public:      virtual ~linearList() {};      virtual bool empty() const = 0;                  // return true iff list is empty      virtual int size() const = 0;                  // return number of elements in list      virtual T& get(int theIndex) const = 0;                  // return element whose index is theIndex      virtual int indexOf(const T& theElement) const = 0;                  // return index of first occurence of theElement      virtual void erase(int theIndex) = 0;                  // remove the element whose index is theIndex      virtual void insert(int theIndex, const T& theElement) = 0;                  // insert theElement so that its index is theIndex      virtual void output(ostream& out) const = 0;                  // insert list into stream out};#endifFile circularListWithHeader.h// circularList list with header node and iterator#ifndef circularListWithHeader_#define circularListWithHeader_#include<iostream>#include<sstream>#include<string>#include "chainNode.h"#include "myExceptions.h"#include "linearList.h"using namespace std;template<class T>class circularListWithHeader{   public:      // 构造函数      circularListWithHeader();      // some methods      bool empty(){return listSize = 0;}      int size() const {return listSize;}      T& get(int theIndex) const;      int indexOf(const T& theElement) const;      void erase(int theIndex);      void insert(int theIndex, const T& theElement);      void output(ostream& out) const;      void reverse();      // iterators to start and end of list      class iterator;      iterator begin() {return iterator(headerNode->next);}      iterator end() {return iterator(headerNode);}            // iterator for chain            class iterator            {               public:                  // typedefs required by C++ for a forward iterator                  typedef forward_iterator_tag iterator_category;                  typedef T value_type;                  typedef ptrdiff_t difference_type;                  typedef T* pointer;                  typedef T& reference;                  // 构造函数                  iterator(chainNode<T>* theNode = NULL)                     {node = theNode;}                  // 解引用操作符                  T& operator*() const {return node->element;}                  T* operator->() const {return &node->element;}                  // 迭代器加法操作                  iterator& operator++()   // preincrement                            {node = node->next; return *this;}                  iterator operator++(int) // postincrement                        {iterator old = *this;                         node = node->next;                         return old;                        }                  // 相等检验                  bool operator!=(const iterator right) const                        {return node != right.node;}                  bool operator==(const iterator right) const                        {return node == right.node;}               protected:                  chainNode<T>* node;            };  // end of iterator class   protected:      void checkIndex(int theIndex) const;            // 如果索引无效,抛出异常      chainNode<T>* headerNode;  // 指向链表第一个元素的指针      int listSize;              // 元素个数};template<class T>circularListWithHeader<T>::circularListWithHeader(){// 构造函数   headerNode = new chainNode<T>();   headerNode->next = headerNode;   listSize = 0;}template<class T>void circularListWithHeader<T>::checkIndex(int theIndex) const{// 确定 theIndex在 0和listSize - 1之间转换.   if (theIndex < 0 || theIndex >= listSize)   {ostringstream s;    s << "index = " << theIndex << " size = " << listSize;    throw illegalIndex(s.str());   }}template<class T>T& circularListWithHeader<T>::get(int theIndex) const{checkIndex(theIndex);chainNode<T>* currentNode = headerNode->next;for(int i = 0;i<theIndex;i++)currentNode = currentNode->next;return currentNode->element;}template<class T>int circularListWithHeader<T>::indexOf(const T& theElement) const{// Return元素theElement首次出现时的索引. // 如果不存在Return -1 .   //将theElement放入headerNode   headerNode->element = theElement;   // 在链表中寻找 theElement   chainNode<T>* currentNode = headerNode->next;//指向链表的第一个   int index = 0;  // 返回的索引,从0开始计数   while (currentNode->element != theElement)   {      // 移动到下一节点      currentNode = currentNode->next;      index++;   }   // 确定是否找到element   if (currentNode == headerNode)      return -1;   else      return index;}template<class T>void  circularListWithHeader<T>::erase(int theIndex){// Delete索引为theIndex的元素. // 如果不存在这样的元素就抛出异常.checkIndex(theIndex);//索引有效,需找要删除的元素节点chainNode<T>* deleteNode;// use p 指向要删除节点的前驱结点chainNode<T>* p = headerNode->next;for(int i = 0;i < theIndex - 1;i++)p = p->next;deleteNode = p->next;p->next = p->next->next;// 删除 deleteNode指向的节点listSize--;delete deleteNode;}template<class T>void circularListWithHeader<T>::insert(int theIndex, const T& theElement){// Insert theElement so that its index is theIndex.   if (theIndex < 0 || theIndex > listSize)   {// 无效索引      ostringstream s;      s << "index = " << theIndex << " size = " << listSize;      throw illegalIndex(s.str());   }   // find 新元素前驱   chainNode<T>* p = headerNode;   for (int i = 0; i < theIndex; i++)      p = p->next;   // insert after p   p->next = new chainNode<T>(theElement, p->next);   listSize++;}template<class T>void circularListWithHeader<T>::output(ostream& out) const{// 把链表放入输出流.   for (chainNode<T>* currentNode = headerNode->next;                      currentNode != headerNode;                      currentNode = currentNode->next)      out << currentNode->element << "  ";}// overload <<template <class T>ostream& operator<<(ostream& out, const circularListWithHeader<T>& x)   {x.output(out); return out;}template<class T>void circularListWithHeader<T>::reverse(){if(listSize <= 1) return;chainNode<T>*currentNode = headerNode->next,*nextNode,*lastNode = headerNode;while(currentNode != headerNode){nextNode = currentNode->next;currentNode->next = lastNode;lastNode = currentNode;currentNode = nextNode;}headerNode->next = lastNode;}File circularListWithHeader.cpp// test the class circularListWithHeader#include<iostream>#include "circularListWithHeader.h"#include<numeric>using namespace std;int main(){   // test constructor   circularListWithHeader<int> y;   // test size   cout <<"Initial size of y  ="        << y.size() << endl;   // test insert   y.insert(0, 2);   y.insert(1, 6);   y.insert(0, 1);   y.insert(2, 4);   y.insert(3, 5);   y.insert(2, 3);   cout << "Inserted 6 integers, list y should be 1 2 3 4 5 6" << endl;   cout << "Size of y = " << y.size() << endl;   y.output(cout);   cout << endl << "Testing overloaded <<" << endl;   cout << y << endl;   // test iterator   cout << endl <<"Ouput using forward iterators pre and post ++" << endl;   for (circularListWithHeader<int>::iterator i = y.begin();          i != y.end(); i++)        cout << *i << "  ";     cout << endl; for(circularListWithHeader<int>::iterator i = y.begin(); i != y.end(); ++i) { cout << *i << "  "; *i += 1; }     cout << endl;   // test indexOf   int index = y.indexOf(4);   if (index < 0) cout << "4 not found" << endl;   else cout << "The index of 4 is " << index << endl;   index = y.indexOf(7);   if (index < 0) cout << "7 not found" << endl;   else cout << "The index of 7 is " << index << endl;   int sum = accumulate(y.begin(), y.end(), 0);//初始值是0      cout << "The sum of the elements is " << sum << endl;    //test reverse    y.reverse();    cout<<y<<endl;   return 0;}#endifFile myExceptions.h// exception classes for various error types#ifndef myExceptions_#define myExceptions_#include <string>using namespace std;// illegal parameter valueclass illegalParameterValue{   public:      illegalParameterValue(string theMessage = "Illegal parameter value")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// illegal input dataclass illegalInputData{   public:      illegalInputData(string theMessage = "Illegal data input")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// illegal indexclass illegalIndex{   public:      illegalIndex(string theMessage = "Illegal index")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// matrix index out of boundsclass matrixIndexOutOfBounds{   public:      matrixIndexOutOfBounds            (string theMessage = "Matrix index out of bounds")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// matrix size mismatchclass matrixSizeMismatch{   public:      matrixSizeMismatch(string theMessage =                   "The size of the two matrics doesn't match")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// stack is emptyclass stackEmpty{   public:      stackEmpty(string theMessage =                   "Invalid operation on empty stack")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// queue is emptyclass queueEmpty{   public:      queueEmpty(string theMessage =                   "Invalid operation on empty queue")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// hash table is fullclass hashTableFull{   public:      hashTableFull(string theMessage =                   "The hash table is full")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// edge weight undefinedclass undefinedEdgeWeight{   public:      undefinedEdgeWeight(string theMessage =                   "No edge weights defined")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};// method undefinedclass undefinedMethod{   public:      undefinedMethod(string theMessage =                   "This method is undefined")            {message = theMessage;}      void outputMessage() {cout << message << endl;}   private:      string message;};#endif


0 0
原创粉丝点击