C++复习第四日(单链表的C++实现 源码和图解)

C++内容复习

在这里插入图片描述

单链表的简单实现图解

在这里插入图片描述

单链表源码

#include <iostream>
#include <assert.h>
using namespace std;
struct node
{
	node(int data = 0)
		:_next(nullptr)
		,_data(data)
	{
	     
	}
	node* _next;
	int _data;
};
class SL
{
public:
	SL()
		:_head(nullptr)
	{}
	void pushfront(int data)
	{
		node* newnode = new node(data);
		if (newnode == nullptr)
		{
			perror("Error of new");
			exit(-1);
		}
		newnode->_next = _head;
		_head = newnode;
	}
	void popfront()
	{
		assert(_head);
		node* newhead = _head->_next;
		delete _head;
		_head = newhead;
	}
	void pushback(int data)
	{
		node* newnode = new node(data);
		if (newnode == nullptr)
		{
			perror("Error of new");
			exit(-1);
		}	
		if (_head == nullptr)
		{
			_head = newnode;
		}
		else
		{
			node* cur = _head;
			while (cur->_next)
			{
				cur = cur->_next;
			}
			cur->_next = newnode;
		}
	}
	void popback()
	{
		assert(_head);
		if (_head->_next == nullptr)
		{
			delete _head;
			_head = nullptr;
		}
		else
		{
			node* pcur = _head;
			node* cur = _head->_next;
			while (cur->_next )
			{
				pcur = cur;
				cur = cur->_next;
			}
			delete cur;
			pcur->_next = nullptr;
		}
	}
	void Insert(node* pos,int data)
	{
		if (pos == _head)  pushfront(data);
		else if (pos == nullptr)pushback(data);
		else {
			node* newnode = new node(data);
			if (newnode == nullptr)
			{
				perror("Error of new");
				exit(-1);
			}
			node* cur = _head;
			while (cur->_next != pos)
			{
				cur = cur->_next;
			}
			newnode->_next = pos;
			cur->_next = newnode;
		}		
	}
	void SLprintf()
	{
		node* cur = _head;
		while (cur)
		{
			cout << cur->_data << " ";
			cur = cur->_next;
		}
		cout << endl;
	}
	node* Find(int data)
	{
		int count = 0;
		node* cur = _head;
		while (cur)
		{
			if (cur->_data == data)
			{
				++count; break;
			}			
			cur = cur->_next;
		}	
		if (!count) { perror("没有找到"); return nullptr; }
		return cur;
	}
public:
	node* _head;
};
int main()
{
	SL s1;
	s1.Insert(nullptr, 1);
	s1.Insert(nullptr, 2);
	s1.Insert(s1.Find(2), 5);
	s1.Insert(nullptr,5);
	s1.popback();
	s1.popback();
	s1.popback();
	s1.popback();  
	cout << (int)s1._head;
	

	s1.SLprintf();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值