数据结构自学之路---单链表

#include <iostream>
using namespace std;
template<typename T> class Node;
//单链表的定义
template<typename T> class List
{
private:
	Node<T> *head;
public:
	List(){
		head=new Node<T>();
	}
	~List(){
		delete head;
	}
	bool insert(int i,T data);   //插入元素
	T getnodedata(int i);        //获取指定元素
	void clean();               //清除链表
	int getlength();            //获取链表长度
	bool deletenode(Node<T> *p);   //删除指定链表内容
};
//链表结点的定义
template<typename T> class Node 
{
private:
	Node<T> *next;
	T data;
public:
	Node(){
		next=NULL;
	}
	Node(T item,Node<T> *newnext=0){
		next=newnext;
		data=item;
	}
	~Node(){
		next=NULL;
	}
	T getdata(){
		return data;
	}
	
	friend class List<T>;
};
//插入元素的实现
template<typename T> bool List<T>::insert(int i,T data){
	Node<T> *p=head;
	int j;
	for (j=1;j<=i-1;j++)
	{
		p=p->next;
		if (p==NULL)
		{
			break;
		}
	}
	if (p==NULL&&j<i-1)
	{
		return false;
	}else{
		Node<T> *node=new Node<T>(data);
		node->next=p->next;
		p->next=node;
		return true;
	}
}
//获取指定下标的数据的实现
template<typename T> T List<T>::getnodedata(int i){
	Node<T> *p=head->next;
	int j;
	for (j=1;j<=i-1;j++)
	{
		p=p->next;
	}
	return p->getdata();
}
//获取链表的长度
template<typename T> int List<T>::getlength(){
	int counter=0;
	Node<T> *p=head->next;
	while (p!=NULL)
	{
		p=p->next;
		counter++;
	}
	return counter;
}
//删除指定的链表元素
template<typename T> bool List<T>::deletenode(Node<T> *p){
	Node<T> *node=head;
	if (p==NULL)
	{
		return false;
	}else{
		while (node->next!=p)
		{
			node=node->next;
		}
		node->next=p->next;
		delete p;
		return true;
	}
}
//清除链表的元素
template<typename T> void List<T>::clean(){
	Node<T> *p=NULL;
	while (p->next!=NULL)
	{
		p=head->next;
		head->next=p->next;
		delete p;
	}
}

void main()
{
	List<int> list;
	for (int i=0;i<10;i++)
	{
		list.insert(i,i*10);
		cout<<list.getnodedata(i)<<" ";
	}
	cout<<endl;
	cout<<list.getlength()<<endl;
	list.clean();
	cout<<endl;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小胖墩有点瘦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值