C++自定义链表操作实现

C++单链表实现与操作详解 链表的基本构成单元是节点(Node),每个节点承载两部分内容:实际存储的数据和指向下一个节点的引用(指针)。这种分离式设计使得链表可以在运行时动态扩展或收缩,而不受固定容量限制。在C++中,我们通常使用struct或class来封装这一逻辑结构。 阅读详情

author openxmp@163.com
链表操作:
1) 插入
2) operator []
3)  翻转(递归)
4) 翻转(非递归)
5) 求长度

#include <iostream>
using namespace std;
#include <stdio.h>



template<typename T>
class List
{
    //A template-parameter shall not be redeclared within its scope
    //(including nested scopes). A template-parameter shall not have the same
    //name as the template name.
    template<typename U> friend List<U> * recursiveReverse ( List<U> * list );
    template<typename U> friend List<U> * noneRecursiveReverse ( List<U> * list );
public:
    List( );
    List( T &value );
    bool push_back( T &value );
    T operator [] ( int index );
    size_t getSize();
    List *getHead( );
    List *getTail( );
    T getValue ();
    void dump( );
public:
    List *mFirstNode;
    List *mNextNode;
    T mValue;
};

template<typename U>
List<U> *
recursiveReverse ( List<U> * list )
{
    static List<U> * firstNode = 0;
    if ( 0 == list ->mNextNode )
    {
        list ->mFirstNode = list;
        firstNode = list;
        return list;
    }
    List<U> * node = recursiveReverse( list -> mNextNode );
    list -> mNextNode->mNextNode = list;
    list -> mNextNode = 0;
    node -> mFirstNode = firstNode;
    return node;
}

template<typename U>
List<U> * noneRecursiveReverse ( List<U> *list )
{
    List<U> * recursiveHead = 0;
    List<U> * nextNode = 0;
    while ( list )
    {
        nextNode = list->mNextNode;
        list->mNextNode = recursiveHead;
        recursiveHead = list;
        list = nextNode;
    }
    recursiveHead->mFirstNode = recursiveHead;
    return recursiveHead;
}

template<typename T>
List<T>::List():mFirstNode(0),mNextNode(0)
{
}

template<typename T>
List<T>::List(T & value)
{
    mValue = value;
}

template<typename T>
bool
List<T>::push_back( T & value )
{
    if ( 0 == mFirstNode )
    {
        mFirstNode = this;
        mNextNode = 0;
        mValue = value;
        return true;
    }
    List *node = new List( value );
    if ( ! node )
    {
        return false;
    }
    node->mFirstNode = mFirstNode;
    node->mNextNode = 0;
    List *lastNode = mFirstNode;
    while ( lastNode ->mNextNode )
    {
        lastNode = lastNode->mNextNode;
    }
    lastNode->mNextNode = node;
    return true;
}

template<typename T>
T
List<T>::operator [] ( int index )
{
    if ( index < 0 || index > getSize() )
    {
        return 0;
    }
    List *theNode = mFirstNode;
    while ( theNode )
    {
        if ( 0 == index )
        {
            return theNode->mValue;
        }
        theNode = theNode ->mNextNode;
        index --;
    }
    return 0;
}

template<typename T>
size_t
List<T>::getSize()
{
    size_t retval = 0 ;
    List * node = mFirstNode;
    while ( node )
    {
        retval ++;
        node = node ->mNextNode;
    }
    return retval;
}

template<typename T>
List<T> *
List<T>::getHead()
{
    return mFirstNode;
}

template<typename T>
List<T> *
List<T>::getTail()
{
    List * theNode = mFirstNode;
    while ( theNode -> mNextNode )
    {
        theNode = theNode->mNextNode;
    }
    return theNode;
}

template<typename T>
T
List<T>::getValue()
{
    return mValue;
}

template<typename T>
void
List<T>::dump()
{
    List * node = mFirstNode;
    cout << " start dump "<<endl;
    while ( node )
    {
        fprintf(stderr,"[value %d] [address %p]\n",node->mValue,node);
        node = node ->mNextNode;
    }
    cout << endl<< " dump finished " << endl;
}

void unitTest()
{
    typedef List<int> INTLIST;
    INTLIST intList ;
    for (int i = 0; i < 10; ++i)
    {
        intList.push_back(i);
    }
    cout << "get Head "<< intList.getHead()->getValue()<<endl;
    cout << "get Tail "<< intList.getTail()->getValue()<<endl;
    INTLIST *reverseResult = recursiveReverse( & intList );
    reverseResult->dump();
    reverseResult = recursiveReverse(reverseResult);
    reverseResult->dump();
    reverseResult = noneRecursiveReverse(reverseResult);
    reverseResult->dump();
}

int main()
{
    unitTest();
    return 0;
}



链表翻转


#include <iostream>
using namespace std;


struct Node
{
    Node(int value):mValue(value),mNextNode(0)
    {


    }
    int mValue;
    Node *mNextNode;
};


Node *reverse(Node *input)
{
    Node *retval = 0;
    Node *nextNode = 0;
    while ( input )
    {
        nextNode = input->mNextNode;
        input ->mNextNode = retval;
        retval = input;
        input = nextNode;
    }
    return retval;
}


void PrintNode ( Node * head )
{
    while ( head )
    {
        cout << head->mValue<<endl;
        head = head->mNextNode;
    }
}


int main(int argc, char const *argv[])
{
    Node *head = 0;
    Node *currentNode = head;
    for (int i = 0; i < 10; ++i)
    {
        Node *tmpNode = new Node(i);
        if ( 0 == i )
        {
            currentNode = tmpNode;
            head = tmpNode;
            continue;
        }
        currentNode->mNextNode = tmpNode;
        currentNode = tmpNode;
    }        
    Node *reverseNode = reverse(head);
    PrintNode(reverseNode);
    return 0;
}


        
自定义链表 自定义链表 已经编译成功! 绝对可用~ 立即下载

相关推荐

QT代码实现list链表结构

QT代码实现list链表结构,资源中包含单向链表和双向链表

QT List链表用法

QList<QString> list; list<<"1"<<"2"<<"3"<<"4"; // 迭代器正序 // QList<QString>::iterator it; // for (it = list.begin(); it != list.end(); ++it) // { // qDebug()<<*it<<endl; // } // 迭...

时越的博客 6178

C++链表类代码(自己写的)

C++的模版类,实现了链表的基本功能,添删改查。

C/C++学习——自定义数据类型——链表

链表的概念 一、链表的概念 1、链表是一种存储空间能动态进行增长或缩小的数据结构。 2、链表主要用于: (1)建立不定长度的数组。 (2)可以在不重新安排整个存储结构的情况下,方便且迅速地插入和删除数据元素。 3、链表广泛应用于数据管理中。 二、结点 struct NODE{//结点数据类型 ElemType data;//数据域 NODE *link;//指针域 }; 1、ElemType 可以是简单的内置数据类型,也可以是复杂的数据类型, typedef struct t

cbb8234078009的博客 2424

常见的电容有哪些

电容在电路板中非常常见,类别纷繁复杂,本文化繁为简,主要介绍下常见电容。

qq_40170041的博客 768

MATLAB实战:5步搞定铣削稳定性叶瓣图(附完整代码解析)

本文提供了一份基于MATLAB的铣削稳定性叶瓣图实战指南。通过5个清晰步骤,从动力学原理出发,详细解析了利用半离散法构建稳定性判据、模块化代码设计、高效参数扫描及高级可视化的完整流程,并附有完整代码,帮助工程师快速预测和规避加工颤振,优化铣削工艺参数。

weixin_29197051的博客 194

c++创造一个链表

刚入门数据结构,尝试一下自己写一个链表

weixin_73000861的博客 961

3分钟接入满血版DeepSeek-R1:字节火山引擎手把手教程!免费50万tokens!

3分钟接入满血版DeepSeek-R1:字节火山引擎手把手教程!免费50万tokens!

hunteritself的博客 2万+

Qt QLinkedList 详解:从底层原理到高级用法

qlinkedlist

探索C++编程的奥秘,分享深入的技术见解和实践,旨在激发读者创造力与解决问题的思维。 4677

火车头采集器超级详细图文使用指导(面向新手)

火车采集器·超级详细使用指导

DE的个人原创笔记 1万+

C++实现链表

【代码】C++实现链表。

yangjinjingbj的博客 410

054_小驰私房菜_Camx i2c读写相关备忘

Camera 对Ae、Af这些控制,实际都是,最终实际都是落实到hal下发相关的指令给驱动,那hal这边是怎么给驱动下发相关命令的呢?#小驰私房菜054# #Qcom Camx#可以参考看下下面相关代码内容。

149

c++模板实现自定义链表及操作

今天花时间整理了一下C++模板方面的

dengchendeng的专栏 1882

YOLOv13改进策略【小目标改进】| Shape-NWD:融合改进,结合Shape-IoU和NWD 更好地适应小目标特性

Bw−wgt2h−hgt2weight2Bweight2w−wgt​2h−hgt​2​其中weight2weight = 2weight2。

Limiiiing的博客 587

完整功能-《网络安全创新实践》:设计并实现一种基于Npcap的网络嗅探器(直接能运行cpp的MFC代码+实验报告)

《网络安全创新实践》:设计并实现一种基于Npcap的网络嗅探器。(直接能跑的MFC)监听所有数据包,以及监听指定IP地址的数据包;(2)能够显示完整的IP数据包首部信息,例如:版本、首部长度、数据包长度、数据包类型(协议字段)、TTL、源IP地址、目的IP地址等;(3)能够显示完整的TCP报文段信息,例如:源端口、目的端口、序号、确认号、数据部分等;(4)能够自动检测SQL注入攻击等Web攻击行为;(5)能够将监听到的数据包信息保存到文件中,以及从文件中读取并显示数据包信息;(6)具有图形化操作界面。

weixin_46531010的博客 660

链表数据结构及基本操作方法的实现:基于C++的类编程

链表数据结构及基本操作方法的实现:基于C++的类编程 LinkList.h 头文件 #pragma once #include &quot;stdafx.h&quot; #include &amp;lt;iostream&amp;gt; using namespace std; struct NODE { int data; NODE* next; }; class LinkList { private: NODE*...

weixin_43975801的博客 230

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

用c/c++自己动手实现一个链表LinkList

链表的特点 便于插入删除,这些操作只要改变指针的指向 遍历查找O(n) 排序复杂度也极大 所以适合插入删除频繁的程序。 实现思想 自建基本的节点数据结构 明确基本操作:初始化、插入、删除、按位置查找、按值查找等等 实现代码 注:vs2008 // LinkList.cpp : Defines the entry point for the console application. //...

一只懒虫的博客 3831

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【C++】从零实现 C++ 自定义 list 容器:双向链表与迭代器深度解析

list容器需要一个迭代器来支持前向和后向遍历。我们设计一个,封装节点指针,并重载->++--等操作符。return tmp;return tmp;代码解读operator*和operator->:分别返回节点的值和地址。++和--:支持前后遍历。==和!:判断两个迭代器是否指向相同节点。本文详细介绍了如何从零实现一个 C++ 双向链表list容器,包括节点结构、迭代器设计、增删操作等。通过这篇文章的学习,希望你对list的底层实现原理有了更深入的理解。C++数据结构与算法:链表详解。

weixin_74837455的博客 3054

深入理解 C++ 链表:原理、实现与高级应用

链表是由节点(Node)组成的线性数据结构,每个节点包含数据域(存储元素值)和指针域(存储相邻节点地址)。这种结构使得链表无需预先分配连续内存空间,可在运行时动态调整大小。在 C++ 中,节点通常通过结构体或类实现,例如单链表节点定义:cpp// 单链表节点结构T data;// 数据域// 指针域,指向下一节点自定义链表需处理动态内存管理newdelete)、边界条件检查(空链表、仅有一个节点等)和操作封装(插入、删除、遍历等)。

zqmgx13291的博客 1017

使用C++实现尾插式循环链表结构

总结起来,这段代码提供了一个简洁而实用的尾插式循环链表的实现,适用于需要高效进行顺序添加和按最近添加顺序删除元素的场景。用于创建新节点并将新节点插入到链表的尾部,即每次新增节点都会成为新的末尾节点。因此有必要实现一款属于自己的双向链表,这样在有需要的时候就能随时增加自己的特性,让链表更好的服务于其他模块。在使用C++实现链表时,我们需要实现两个主要的类:1. node节点类 ,2. 链接node节点的类。,该节点的前驱和后继均指向自身,形成一个空链表的“闭环”。,它作为链表中的实际节点实现。

andrewbytecoder 782

C++实现单向链表

LinkList.h #include <windows.h> #include <stdio.h> // 链表结点 typedef struct LINKNODE { void* data; // 可以指向任何类型的数据 LINKNODE* next; }LinkNode; // 链表结构体 typedef...

weixin_30824599的博客 135

C++链表解析:从基础原理到高级应用,全面掌握链表的使用

C++链表解析:从基础原理到高级应用,全面掌握链表的使用

探索C++编程的奥秘,分享深入的技术见解和实践,旨在激发读者创造力与解决问题的思维。 1880

C++数据结构X篇_05_企业链表的思路和实现(企业链表是企业中经常使用的一种链表;企业链表p_next仅仅指向下一个p_next的地址,链表中并未涉及任何data数据)

/链表指针节点节点 class node_p {public ://链表 class list {public :int size;//初始化链表 list * list_init() {return L;//自定义链表数据节点 class my_data {public :int num;当我们创建my_data的对象指针p1,将其强转成node_p的对象指针a1,a1->next=p1->p_data(具体原理见。

分享学习成长历程,Winter is coming! 365
上一篇: C++操作符重载总结
下一篇: C++快速排序模板法
乔巴好萌
博客等级 码龄15年 228粉丝 47原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值