通过class与类模板进行c++ stl的list的封装

  • Post author:
  • Post category:其他


      template<typename>类型参数1,typename 类型参数2。。。
返回值 函数名 (参数列表)、
{
   return 返回值;
}

template<typename T>
T find(T* arr,size_t len)
{
    return val;
}
可以任何标识符作为类型参数名,但使用'T'是俗城约定的,它表示调用这个函数时所指定的任意类型。

#include

using namespace std;

template

class Node

{


public:

Node(T data):data(data)

{


next = NULL;

}

T data;
Node* next;

};

template

class List

{


Node* head;

size_t len ;

public:

List(void)

{


len=0;

head = NULL;

}

bool empty(void)
{
	return head == NULL;	
}

void pop_front(void)
{
	Node<T>* temp = head;
	head = head->next;
	delete temp;
    len--;
}

void push_front(const T& data)
{
	Node<T>* node = new Node<T>(data);
	node->next = head;
	head = node;
    len++;
}

void push_back(const T& data)
{
	if(len==0)
	{
     push_front(data);
	}
	else
	{
	Node<T>* node = new Node<T>(data);
    Node<T>* _node;
    for(_node=head;_node->next!=NULL;_node=_node->next);
	_node->next=node;
    }
	len++;
}

size_t size(void)
{
	return len;
}
T& front(void)
{
	return head->data;
}
T& back(void)
{
    Node<T>* node;
    for(node=head;node->next!=NULL;node=node->next);
	return node->data;
}
void clear(void)
{
	for(Node<T>* node=head;node;node=node->next)
	{
		delete node;
	}
	len=0;
}

};

int main()

{


List s;

for(int i=1; i<10; i++)

{


s.push_back(i);

cout << s.back() << endl;

}

cout << “———-” << endl;

s.clear();

while(!s.empty())

{


cout << s.back() << endl;

s.pop_front();

}

}



版权声明:本文为qq_45067278原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。