第一篇blog,请各位多多指教~~
直接上代码:
.h头文件
#ifndef LINKLIST_H
#define LINKLIST_H
#include <iostream>
#include <array>
struct Node{
double data;
Node *next = nullptr;
};
class LinkList
{
public:
LinkList();
~LinkList();
void InitCreate(int num);//创建长度为num的链表
void Remove(double value);
void Insert(double value, int pos);
int Find(double value);
void ListReverse();//反转链表
void Show();//输出链表中各个节点的值
int GetLength();
private:
Node *head;
int length;
double array[10];
};
#endif // LINKLIST_H
.cpp文件
#include "linklist.h"
LinkList::LinkList():length(0)
{
head = nullptr;
for(int i = 0; i < sizeof(array)/sizeof(array[0]); ++i){
array[i] = i + i/10;
}
}
LinkList::~LinkList()
{
Node *temp;
for(int i=0;i<length;i++)
{
temp=head;
head=head->next;
delete temp;
}
}
void LinkList::InitCreate(int num)
{
if(num <= 0){
return;
}
head = new Node;
Node *tmp = head;
Node *ptr = nullptr;
for(int i = 0; i < num-1; ++i){
tmp->data = array[i];
ptr = new Node;
tmp->next = ptr;
tmp = ptr;
length++;
}
tmp->data = array[num - 1];
length++;
tmp->next = nullptr;
}
void LinkList::Remove(double value)
{
int pos = Find(value);
if(pos < 0){
std::cout<<"don't have this value !!"<<std::endl;
return;
}
if(pos == 0){
head = head->next;
length--;
return;
}
Node *tmp = head;
int index = 1;
while(index < pos){
tmp = tmp->next;
index++;
}
Node *p = tmp->next;
tmp->next = tmp->next->next;
delete p;
length--;
}
void LinkList::Insert(double value, int pos)
{
if(pos < 0){
std::cout<<"pos should greater than zero !\n";
return;
}
Node *tmp = head;
Node *new_tmp = new Node;//新节点
new_tmp->data = value;
//插入到零节点的位置
if(pos == 0){
new_tmp->next = head;
head = new_tmp;
length++;
return;
}
//插入到大于零节点的位置
int index = 1;
while(tmp != nullptr && index < pos){
tmp = tmp->next;
index++;
}
if(tmp == nullptr){
std::cout<<"insert failed !!";
return;
}
new_tmp->next = tmp->next;
tmp->next = new_tmp;
length++;
}
int LinkList::Find(double value)
{
Node *tmp = head;
int index = -1;
while(tmp != nullptr){
index++;
if(tmp->data == value){
return index;
}
tmp = tmp->next;
}
return -1;
}
void LinkList::ListReverse()
{
if(head == nullptr){
std::cout<<"list is empty!!";
return;
}
Node *tmp, *p_tmp = nullptr;
tmp = head->next;
while(head){
tmp = head->next;
head->next = p_tmp;
p_tmp = head;
head = tmp;
}
head = p_tmp;
}
void LinkList::Show()
{
Node *p = nullptr;
if(head == nullptr){
return;
}
p = head;
int i = 0;
while(p != nullptr){
std::cout<<"data["<<i<<"]: "<<p->data<<std::endl;
i++;
p = p->next;
}
}
int LinkList::GetLength()
{
return length;
}
PS:InitCreate函数是为了想尽快创建一个链表,进行后续操作。