将链表类做成工具类

本文详细介绍了一个简单的单链表数据结构的实现过程,包括头文件的定义与成员函数的具体实现,并通过一个测试示例验证了链表的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.先做头文件List.h  ,注意预编译处理

#ifndef LIST__H__
#define LIST__H__

#include <iostream>
#include <stdexcept>
using namespace std;

typedef int T;
class List
{
private:
	struct Node
	{
		T data;
		Node* next;
		Node(const T& d):data(d),next()
		{

		}
	};
	Node* head;
	int sz;
	Node*& getptr(int pos);
public:
	List():head(),sz()
	{

	}
	
	~List()
	{
		clear();
	}

	List& insert(const T& d,int pos = 0);
	void travel();
	void clear();
	bool erase(int pos);
	void remove(const T& d);
	bool set(const T& d,int pos);
	int find(const T& d);
	int size()
	{
		return sz;
	}

	T& at(int pos);
	void push_front(const T& d)
	{
		insert(d,0);
	}
	
	void push_back(const T& d)
	{
		insert(d,sz);
	}

	void pop_front()
	{
		erase(0);
	}

	void pop_back()
	{
		erase(sz-1);
	}
};

#endif

2.再做cpp文件 ,注意这里没有main函数,除了函数的定义外,只包含了List.h文件


#include "List.h"
List::Node*& List::getptr(int pos)
{
	if(pos < 0 || pos > sz)
	{
		pos = 0;
	}
	if(pos == 0) 
	{
		return head;
	}

	Node* p = head;
	
	for(int i = 0; i < pos -1 ; i++)
	{
		p = p->next;
	}
	
	return p->next;
}

List& List::insert(const T& d,int pos)
{
	Node* pn = new Node(d);
	Node*& ptr = getptr(pos);
	pn->next = ptr;
	ptr = pn;
	sz++;
	return *this;
}

void List::travel()
{
	Node* p = head;
	while(p)
	{
		cout << p->data << ' ' ;
		p = p->next;
	}
	cout << endl;
}

void List::clear()
{
	Node* p = head;
	while(head)
	{
		head = head->next;
		delete p;
		p = head;
	}
	sz = 0;
}

bool List::erase(int pos)
{
	if(pos < 0 || pos >= sz)
	{
		return false;
	}
	Node*& ptr = getptr(pos);
	Node* p = ptr;
	ptr = ptr->next;
	delete p;
	sz--;
	return true;
}

int List::find(const T& d)
{
	int pos = 0;
	Node* p = head;
	while(p)
	{
		if(p->data == d)
		{
			return pos;
		}
		//曾经把下面两行写入了if
		p = p->next;
		pos++;
	}
	return -1;
}

void List::remove(const T& d)
{
	int pos;
	while((pos = find(d)) != -1)
	{
		erase(pos);
	}
}

bool List::set(const T& d,int pos)
{
	if(pos < 0 || pos >= sz)
	{
		return false;
	}

	Node*& ptr = getptr(pos);
	ptr->data = d;
	return true;
}

T& List::at(int pos)
{
	if(pos < 0 || pos >= sz)
	{
		throw out_of_range("out");
	}
	//曾把下两句写到了if
	Node*& ptr = getptr(pos);	
	return ptr->data;
}


3.最后做一个测试的cpp  ,这里要注意头文件的包含

想要程序运行,首先编译List.cpp    ==>  g++ -c List.cpp

然后编译test.cpp  ==> g++ -c test.cpp

接着连接  ==> g++ List.o test.o

最后执行 ==> ./a.out

哦了。

#include <iostream>
#include "List.h"

int main()
{
	List list;
	list.insert(10);
	list.travel();
	cout << "好了,已经将List做成头文件和cpp文件了,以后可以将其当作工具类了。测试结束。" << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值