挺久没写了,学的也很浅,如果写错了希望帮忙指正,谢谢!
Node.h
#include<iostream>
#ifndef NODE
#define NODE
using namespace std;
class Node
{
public:
int iValue;//default type is private
Node *next;
Node();
Node(int iVal):iValue(iVal),next(NULL){};
int iGetValue();
void vSetValue(int iValue);
//~Node();不能声明了不实现,会报错: 无法解析的外部符号 "public: __thiscall Node::~Node(void)" (??1Node@@QAE@XZ)……
};
#endif
Node.cpp
#include"Node.h"
int Node::iGetValue()
{
return this->iValue;
}
void Node::vSetValue(int iValue)
{
this->iValue = iValue;
}
Linklist.h
#include<iostream>
#include"Node.h"
#ifndef LINKLIST
#define LINKLIST
using namespace std;
class Linklist
{
Node *headNode;
Node *nextNode;
public:
Linklist();
void vAddNode(int iVal);
void vDeleteNode(int iVal);
void vShowNode();
~Linklist();
};
#endif
Linklist.cpp
#include"Linklist.h"
Linklist::Linklist()
{
Node *headNode = new Node(0);
this->headNode = headNode;
nextNode = headNode;
//delete head;
}
void Linklist::vAddNode(int iVal)
{
Node *newNode = new Node(iVal);
nextNode->next = newNode;
nextNode = newNode;
}
void Linklist::vDeleteNode(int iVal)
{
bool bIsVal;
Node *delNode;
Node *current = headNode;
bIsVal = false;
while(current->next != NULL)
{
if(current->next->iValue == iVal)
{
bIsVal = true;
delNode = current->next;
current->next = current->next->next;
delete delNode;
delNode = NULL;
break;
}
}
if(bIsVal)
{
cout << "删除成功" << endl;
}
else
{
cout << "不存在此值" << endl;
}
}
void Linklist::vShowNode()
{
Node *current = headNode;
while(current->next != NULL)
{
cout << current->next->iValue << " ";
current = current->next;
}
cout << endl;
}
Linklist::~Linklist()
{
Node *delNode;
while(headNode->next != NULL)
{
delNode = headNode;
headNode = headNode->next;
delete delNode;
delNode = NULL;
}
delete headNode; //创建时创建了一个
headNode = NULL;
nextNode = NULL;
}
Using.cpp
#include<iostream>
#include"Linklist.h"
using namespace std;
int main()
{
Linklist *link = new Linklist();
link->vAddNode(3);
link->vAddNode(5);
link->vDeleteNode(3);
link->vShowNode();
delete link;
link = NULL;
return 0;
}