双向非循环带头结点的链表
图好像有点丑~~
下列是相关操作的代码(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