最近使用C++实现数据结构链表,记录一下方便以后复习,若有错误,敬请指正,
1、创建头结点
链表的基本节点是Node,首先手动创建一个Node
struct Node
{
int data;
Node *next;
Node(const int& da) :data(da), next(nullptr){}
};
Node的变量一共有两个,将next指针置为NULL。
2、创建链表
先给出程序,再做注释
#ifndef _LIST_H
#define _LIST_H
class ListCode
{
public:
ListCode();
~ListCode();
bool isEmpty();
void create_List();
void insert(const int &d);
void print();
void delete_List(const int &d);
void update(const int &da, const int &dl);
void insert_pos(const int &da, const int &dl);
private:
struct Node
{
int data;
Node *next;
Node(const int& da) :data(da), next(nullptr){}
};
Node *head ;//头结点
//清理链表
void clear()
{
Node *p = head;
while (p)
{
Node *q = p->next;
delete p;
p = q;
}
}
};
#endif
定义链表的一个头结点head,声明七个成员函数,其含义均可见名知义,定义一个清理的clear()函数,在析构函数中调用,在程序运行结束后,delete掉链表指针。
3、.cpp实现函数
#include "ListCode.h"
#include<iostream>
using namespace std;
ListCode::ListCode()
{
}
ListCode::~ListCode()
{
clear();
}
//创建头结点
void ListCode::create_List()
{
head =new Node(NULL);
}
//从头插入一个节点
void ListCode::insert(const int &d)
{
Node *p = new Node(d);
p->next = head->next;
head->next = p;
}
//判空
bool ListCode::isEmpty()
{
Node *p = head;
if (p->next == NULL)
{
return true;
}
else
{
return false;
}
}
//在某个节点前插入数据
void ListCode::insert_pos(const int &da, const int &dl)
{
Node *p = head, *q = head;
Node *n =new Node(dl);
if (isEmpty() == false)
{
while (p != NULL&&p->data != da)
{
q = p;
p = p->next;
}
//q->next = p->next;
q->next = n;
n->next = p;
}
else
{
cout << "链表为空" << endl;
}
}
//打印链表
void ListCode::print()
{
if (isEmpty() == false)
{
cout << "输出链表" << endl;
for (Node *p = head->next; p != nullptr; p = p->next)
{
cout <<p->data <<"--";
}
cout << endl;
}
else
{
cout << "链表为空" << endl;
}
}
//删除节点
void ListCode::delete_List(const int &d)
{
Node *p = head,*q=head;
if (isEmpty() == false)
{
while (p != NULL&&p->data != d)
{
q = p;
p = p->next;
}
q->next = p->next;
delete p;
}
else
{
cout << "链表为空" << endl;
}
}
//修改指定数据
void ListCode::update(const int &da,const int &dl)
{
Node *p = head;
if (isEmpty() == false)
{
while (p != NULL&&p->data != da)
{
p = p->next;
}
p->data = dl;
cout << "修改完成,当前数据为:" << p->data << endl;
}
else
{
cout << "链表为空" << endl;
}
}
4、main函数
#include"ListCode.h"
#include<iostream>
using namespace std;
int main()
{
ListCode list;
list.create_List();
list.insert(30);
list.insert(50);
list.insert(60);
list.insert(70);
list.insert_pos(50, 2);
list.print();
list.delete_List(50);
list.print();
list.update(60, 10);
list.print();
system("pause");
}
5、运行结果