C++ 单向链表

单向链表的核心逻辑

单向链表的每个节点存储当前的值和指向下个节点的指针,插入一个节点的时候需要找到最后一个节点。

#include "log.h"

#ifndef YGQ_TAG
#define YGQ_TAG

template<class E>
struct Node {
    E value;
    Node<E> *next;

    Node(E value, Node<E> *next) {
        this->value = value;
        this->next = next;
    }
};

template<class E>
class LinkedList {
private:
    int len = 0;
    Node<E> *head = nullptr;
public:
    void push(E e);

    Node<E> *findNode(int index);

    E get(int index);

    int size();
};

template<class E>
E LinkedList<E>::get(int index) {
    return findNode(index)->value;
}

template<class E>
Node<E> *LinkedList<E>::findNode(int index) {
    Node<E> *last = head;
    for (int i = 0; i < index; i++) {
        last = last->next;
    }
    return last;
}

template<class E>
int LinkedList<E>::size() {
    return len;
}

template<class E>
void LinkedList<E>::push(E e) {
    LOGI("push before linkedList size:%d", len);
    Node<E> *new_node = new Node<E>(e, nullptr);
    if (head) {
        Node<E> *last = findNode(len - 1);
        last->next = new_node;
    } else {
        head = new_node;
    }
    len++;
}

#endif

运行效果

断点调试效果

打印结果

push before linkedList size:0
push before linkedList size:1
push before linkedList size:2
index:0,value:0
index:1,value:1
index:2,value:2

Demo源码

https://github.com/treech/NDKDemo

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容