用C++类实现 双向非循环带头结点的链表

双向非循环带头结点的链表

在这里插入图片描述
图好像有点丑~~在这里插入图片描述

下列是相关操作的代码(C++ 类封装)

#pragma once
#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;

//对一个结点进行封装
class Node {
   
public:
	Node* _next;
	Node* _pre;
	int _data;
};

//双向非循环链表
class SList {
   
public:
	SList(){
   
		_head = new Node;
		
		_head->_pre = nullptr;
		_head->_next = nullptr;
		_head->_data = 0;
	}
	~SList() {
   
		delete _head;
		_head = nullptr;
	}
	//尾插
	void SListPushBack(int data) {
   
		Node* node = new Node;
		node->_data = data;

		//只存在头结点
		if (_head->_next == nullptr) {
   
			node->_pre = _head;
			node->_next = nullptr;
			_head->_next = node;
		}
		else {
   

			//找到最后一个结点
			Node* cur = _head->_next;
			while (cur->_next != nullptr) {
   
				cur = cur->_next;
			}
			//进行插入
			node->_next = nullptr;
			node->_pre = cur;
			cur->_next = node;
		}
	}
	//尾删
	void SListPopBack() {
   
		if (_head->_next == nullptr) {
   
			return;
		}

		//找到倒数第二个结点
		Node* cur = _head->_next;
		while (cur->_next->_next != nullptr) {
   
			cur = cur->_next;
		}
		Node* node = cur->_next;
		node->_pre = nullptr;
		delete node;
		cur->_next = nullptr;
	}
	//头插
	void SListPushFront(int data) {
   
		Node* node = new Node;
		node->_data = data;
	
		//如果只有头结点 
		if (_head->_next == nullptr) {
   
			node->_next = nullptr;
			node->_pre = _head;
			_head->_next = node;
		}
		//至少有一个结点
		node->_next = _head->_next
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序猿的温柔香

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

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

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

打赏作者

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

抵扣说明:

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

余额充值