头文件


//节点结构 SingleLink.h class Node { public: int data; Node* next; public: Node() = default; Node(int value, Node* next) : data(value), next(next) {} }; //单链表 class SingleLink { public: typedef Node * NodePointer; SingleLink(); ~SingleLink(); int size(); bool isEmpty(); Node* insert(int index, int t); int get(int index); Node* getHead(); //获取链表头节点-初始化的时候,要用头节点来标志已经初始化后的对象 Node* getNode(int index); //获取指定位置的节点 private: int count; Node* first; }; //默认构造函数 SingleLink::SingleLink() :count(0), first(nullptr) { //创建头节点 first = new Node(); first->next = nullptr; }; //返回指定索引的前一个位置节点,若链表为空,则返回头节点 Node* SingleLink::getNode(int index) { if (index > count || index < 0) return nullptr;// nullptr是c++11中用于指代空指针的null变型 int temp = 0; Node* preNode = first; while (temp < index) { temp++; preNode = preNode->next; } return preNode; } //析构函数 SingleLink ::~SingleLink() { Node* pNode = first->next; while (nullptr != pNode) { Node* temp = pNode; pNode = pNode->next; delete temp; } //进行销毁 }; //返回链表的大小 int SingleLink::size() { return count; }; //链表判空 bool SingleLink::isEmpty() { return count == 0; }; Node* SingleLink::getHead() { // 头指针之后的那一个才是头节点 return first->next; } //在指定位置插入新节点 Node* SingleLink::insert(int index, int t) { Node* preNode = getNode(index); if (preNode) { Node* newNode = new Node(t, preNode->next); //构建新节点,构建时指明节点的next节点 preNode->next = newNode; count++; return newNode; } return nullptr; };

调用 LinkListTest.cpp


\#include <iostream> #include<stdarg.h> #include "LinkList.h" int main() { std::cout << "Hello World!\n"; SingleLink list; for (int i = 0; i < 10; i++) { list.insert(i, i*2); } std::cout << "list.size = " << list.size() <<"\n"; SingleLink::NodePointer ptr = list.getHead(); while (ptr != nullptr) { std::cout << ptr->data << " " ; ptr = ptr->next; } //list.print(); }

发表评论

电子邮件地址不会被公开。 必填项已用*标注