c++模板庫-線性表的順序存儲

測試框架:

// c++模板庫-順序存儲.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
//#include"SList.h"
#include"SList.cpp"
#include<iostream>
using namespace std;
struct Teacher
{
	char name[64];
	int age;
};

int main1()
{
	Teacher t1, t2, t3, t4, t5,tmp;
	t1.age = 21;
	t2.age = 22;
	t3.age = 23;
	t4.age = 24;
	t5.age = 25;
	SList<Teacher> list(10);
	list.Inster(t1,0);
	list.Inster(t2, 0);
	list.Inster(t3, 0);
	list.Inster(t4, 0);
	list.Inster(t5, 0);
	for (int i = 0; i < list.Get_Length(); i++)
	{
		list.Get(i,tmp);
		cout << tmp.age << " ";
	}
	//鏈表的銷燬
	while (list.Get_Length()>0)
	{
		list.Delete(0,tmp);
		cout << tmp.age << " ";
	}
	cout << "Hello,,," << endl;
	system("pause");

    return 0;
}
int main2()
{
	Teacher t1, t2, t3, t4, t5;
	Teacher *p1, *p2, *p3, *p4, *p5;
	Teacher* tmp;
	t1.age = 21;
	t2.age = 22;
	t3.age = 23;
	t4.age = 24;
	t5.age = 25;
	p1 = &t1;
	p2 = &t2;
	p3 = &t3;
	p4 = &t4;
	p5 = &t5;

	SList<Teacher*> list(10);
	list.Inster(p1, 0);
	list.Inster(p2, 0);
	list.Inster(p3, 0);
	list.Inster(p4, 0);
	list.Inster(p5, 0);
	for (int i = 0; i < list.Get_Length(); i++)
	{
		list.Get(i, tmp);
		cout << tmp->age << " ";
	}
	//鏈表的銷燬
	while (list.Get_Length()>0)
	{
		list.Delete(0,tmp);
		cout << tmp->age << " ";
	}
	cout << "Hello,,," << endl;
	system("pause");

	return 0;
}
void main()
{
	//main1();
	main2();
}

頭文件
#pragma once

template<typename T>
class SList
{
public:
	SList(int capacity);
	~SList();

	/*SList * List_Create1(int capacity);
	void List_Destory1(SList* list);*/
	//void List_Clear1(SList* list);
	int Get_Length();
	int Get_Capacity();
	int Get(int pos,T &t);
	int Inster( T &t, int pos );
	int Delete(int pos, T &t);
private:
	int length;
	int capacity;
	T *pArray;//數組

	//unsigned int **node; 
};
頭文件的實現:
#include "SList.h"


template<typename T>
SList<T>::SList(int capacity)
{
	//T *pArray;//數組
	pArray = new T[capacity];
	this->capacity = capacity;
	this->length = 0;
}

template<typename T>
SList<T>::~SList()
{
	delete[] pArray;
	pArray = nullptr;
	length = 0;
	capacity = 0;
}
template<typename T>
int SList<T>::Get_Length()
{
	return this->length;
}
template<typename T>
int SList<T>::Get_Capacity()
{
	return this->capacity;
}
template<typename T>
int SList<T>::Get(int pos, T &t)
{
	if (pos<0)
	{
		return -1;
	}
	t = pArray[pos];
	return 0;
}
template<typename T>
int SList<T>::Inster(T &t, int pos)
{
	int i = 0;
	if (pos<0)
	{
		return -1;
	}
	//1 元素後移
	for ( i = length; i > pos; i--)
	{
		pArray[i] = pArray[i - 1];
	}
	pArray[i] = t;
	this->length++;

	return 0;
}
template<typename T>
int SList<T>::Delete(int pos, T &t)
{
	t = pArray[pos];
	int i = 0;
	for ( i = pos+1; i < this->length; i++)
	{
		pArray[i - 1] = pArray[i];
	}
	length--;
	return 0;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章