求链表中的最大值,节点个数,平均值

//头文件
#ifndef LIST_H
#define LIST_H

#include
#include
using namespace std;
template
class LinkNode{
public:
	T data;
	LinkNode* link;
	LinkNode()
	{

	}
	LinkNode(const T& item,LinkNode*ptr=NULL){
		data = item;
		link = ptr;
	}
};
template
class List{

private:
	LinkNode* head;
	LinkNode* currPos;
public:
	List();
	~List();
	void Append(const T value);//为链表赋值,规定链表长度
	void clear();
	void print();
	void HeadToTail();//将链表倒置


	
	T MaxValue();
	int Count();
	T Average();
};
template
T List::MaxValue()
{
	T maxValue = 0;
	LinkNode* p = head;
	while (p != NULL)
	{
		if (maxValue < (p->data))
			maxValue = p->data;
		p = p->link;
	}
	return maxValue;
}

template
int List::Count()
{
	int count = 0;
	LinkNode* p = head;
	while (p != NULL)
	{
		p = p->link;
		count++;
	}
	return count;
}

template
T List::Average()
{
	T average = 0;
	T sum = 0;
	LinkNode* p = head;
	while (p != NULL)
	{
		sum += (p->data);
		p = p->link;
	}
	return average = (sum / Count());
}


template
List::List()
{
	//默认构造函数
	head = NULL;
	currPos = NULL;
}

template
List::~List()
{
	clear();
}

template
void List::Append(const T value)
{
	if (head == NULL)
	{
		head = new LinkNode(value);
		currPos = head;
	}
	else
	{
		LinkNode* p = currPos;
		p->link = new LinkNode(value);
		p = p->link;
		p->link = NULL;
		currPos = p;
	}
}

template
void List::clear()
{
	LinkNode* p = head;
	while (p->link != NULL)
	{
		p = p->link;
		delete head;
		head = p;
	}
}

template
void List::print()
{
	LinkNode* p = head;
	while (p != NULL)
	{
		cout << p->data << " ";
		p = p->link;
	}
	cout << endl;
}

template
void List::HeadToTail()
{
	int top = -1;
	stacktemp;
	LinkNode* p = head;
	while (p != NULL)
	{
		temp.push(p->data);
		p = p->link;
	}
	p = head;
	while (p != NULL)
	{
		p->data = temp.top();
		p = p->link;
		temp.pop();
	}
}


#endif

//主函数
#include"List.h"

int main(int argc, char argv[])
{
	Listlist;
	int count;
	cout << "请输入单链表的长度:";
	cin >> count;
	int value;
	for (int i = 0; i < count; i++)
	{
		cin >> value;
		list.Append(value);
	}
	/*list.print();
	list.HeadToTail();
	list.print();*/
	int maxValue = list.MaxValue();
	cout << "最大值:" << maxValue << endl;
	int listCount = list.Count();
	cout << "链表的节点数:" << listCount << endl;
	int average = list.Average();
	cout << "平均数:" << average << endl;
	return 0;
}
展开阅读全文

没有更多推荐了,返回首页