chainNode.h
#pragma once
#include<iostream>
template<class T>
struct chainNode
{
T element;
chainNode<T>* next;
chainNode<T>* front;
chainNode(){}
chainNode(const T& element, chainNode<T>* next = NULL,chainNode<T>*front = NULL) {
this->element = element;
this->next = next;
this->front = front;
}
};
chain.h
#pragma once
#include<iostream>
using namespace std;
#include"chainNode.h"
#include"myExceptions.h"
template<class T>
class chain
{
public:
chain();
~chain();
bool empty()const;
int size()const;
T& get(int theIndex)const;
void push(const T& theElement);
void reverse();
void output()const;
private:
void checkIndex(int theIndex)const;
chainNode<T>* headNode;
chainNode<T>* tailNode;
int listSize;
};
chain.cpp
#include "chain.h"
template<class T>
chain<T>::chain()
{
headNode = new chainNode<T>();
tailNode = headNode;
listSize = 0;
}
template<class T>
chain<T>::~chain()
{
for (int i = 0; i <= listSize; i++) {
chainNode<T> *nextNode = headNode->next;
delete headNode;
headNode = nextNode;
}
}
template<class T>
bool chain<T>::empty() const
{
return listSize == 0;
}
template<class T>
int chain<T>::size() const
{
return listSize;
}
template<class T>
T& chain<T>::get(int theIndex) const
{
checkIndex(theIndex);
chainNode<T>* cur = headNode->next;
for (int i = 0; i < theIndex; i++) {
cur = cur->next;
}
return cur->element;
}
template<class T>
void chain<T>::push(const T& theElement)
{
chainNode<T>* nextNode = new chainNode<T>(theElement);
tailNode->next = nextNode;
nextNode->front = tailNode;
nextNode->next = headNode;
headNode->front = nextNode;
tailNode = nextNode;
listSize++;
}
template<class T>
void chain<T>::reverse()
{
chainNode<T> *pre = headNode;
chainNode<T> *cur = headNode->next;
while (cur != headNode) {
chainNode<T> *nextNode = cur->next;
cur->next = pre;
pre->front = cur;
pre = cur;
cur = nextNode;
}
headNode->next = pre;
pre->front = headNode;
tailNode = cur;
}
template<class T>
void chain<T>::output() const
{
cout << "头节点地址:" << headNode << "\n";
chainNode<T>*cur = headNode;
for (int i = 0; i < listSize; i++) {
cur = cur->next;
cout << i + 1 << "号节点地址:" << cur << " 该节点值为:" << cur->element << "\n";
}
}
template<class T>
void chain<T>::checkIndex(int theIndex )const
{
if (theIndex < 0 || theIndex >= listSize) {
string str = " size = " + listSize;
throw illegalIndex(str);
}
}
test.cpp
#include <iostream>
using namespace std;
#include"chain.h"
#include"chain.cpp"
int main()
{
int t;
chain<int> mychain;
for (int i = 0; i < 5; i++) {
cin >> t;
mychain.push(t);
}
mychain.output();
mychain.reverse();
mychain.output();
return 0;
}