栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++模板链表类例题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++模板链表类例题

定义一个链表类List3,其结构中私有数据成员如下表:

对以上三个链表的具体要求如下:

         1.定义构造函数和析构函数

         2.输出数据成员函数  void display( );

         3.返回链表长度函数   int Length( );

         4.在链表尾追加一个节点,数据值为t, 返回值是在链表中的位置: 

int Append( const Type &t);

         5.在链表中的第i个位置插入一个节点,数据为t, 返回值表示是否成功 

int Insert(const Type &t , int i);

         6.将链表进行冒泡排序  void BubbleSort( );

         7.在链表中检索数据值为t的节点,并返回其位置信息  int Search( Type &t );

         8.对数组下标运算符重载,以实现对象对成员数组元素的访问  Type & operator [ ] (int i);

#include
using namespace std;
template
class Node {
public:
	Type Data;
	Node* next;
};
template
class List3 
{//public Node {
private:
	Node* head;
	int Length;
public:
	void Get() {
		cout << head->next->Data<;
		head->Data = -1;
		head->next = NULL;
		Length = 1;
	}
	int length() {
		return Length;
	}
	int Append(const Type& t) {
		Node* p,*q;
		p = head;
		while (p ->next!= NULL) {
			p = p->next;
		}
		q = new Node;
		q->Data = t;
		q->next = NULL;
		p->next = q;
		Length++;
		return Length;
	}
	int Insert(const Type& t, int i) {
		Node* p, * q;
		p = head;
		for (int loc = 0; loc < i-1; loc++) {
			p = p->next;
		}
		q = new Node;
		q->Data = t;
		q->next = p->next;
		p->next = q;
		Length++;
		return Length;
	}
	void BubbleSort() {
		for (int i = 0; i < Length; i++) {
			Node* p, * q;
			Type k;
			p = head;
			for (int j = 0; j < Length - 1; j++) {
				q = p->next;
				if (q->Data < p->Data) {
					k = p->Data;
					p->Data = q->Data;
					q->Data = k;
				}
				p = p->next;
			}
		}
	}
	int Search(Type& t) {
		Node* p;
		p = head;
		int i = 0;
		while(p != NULL) {
			i++;
			if (p->Data == t) {
				return i;
			}
			p = p->next;
		}
		return 0;
	}
	Type& operator [ ] (int i) {
		Node* p;
		p = head;
		for (int j = 0; j < i; j++) {
			p = p->next;
		}
		return p->Data;
	}
	void Display() {
		Node* p;
		p = head;
		while (p != NULL) {
			cout << p->Data << " ";
			p = p->next;
		}
		cout << endl;
	}
};
int main() {
	List3 L;
	int n;
	//cin >> n;
	L.Append(70);
	L.Append(3);
	L.Append(5);
	L.Append(1);
	L.Append(8);
	L.Display();
	L.BubbleSort();
	L.Display();
	L.Insert(55, 3);
	L.Display();
	cout< 

注:1:链表头赋值为-1,方便排序的进行,也更方便数据的存取 

      2:以上主函数代码均为测试代码,可以进行后续完善(如添加菜单)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/935795.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号