【数据结构】建立双循环链表实验作业-04

在这里插入图片描述
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;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值