本文通过C++实现C++单链表相关操作:初始化、插入、删除、打印等操作。
#pragma once
#include <iostream>
//定义节点
typedef struct Node {
int value;
Node* next;
};
typedef Node* pNode;
class CListTest
{
public:
CListTest() {
Head = new Node();
Head->next = NULL;
}
~CListTest();
public:
//初始化链表
void createList(int* array, int len);
//插入一个节点
bool insertNode(int location, int value);
//删除一个节点
bool deleteNode(int location);
//链表长度
int getLength();
//打印链表
void printList();
private:
pNode Head;
};
#include "ListTest.h"
CListTest::~CListTest()
{
pNode p = Head;
pNode temp;
while (p) {
temp = p;
p = p->next;
delete temp;
}
}
void CListTest::createList(int* array, int len)
{
pNode tHead = Head;
for (int i = 0; i < len; i++)
{
pNode temp = new Node;
temp->value = array[i];
temp->next = NULL;
tHead->next = temp;
//子函数中tHead的值改变,不会影响Head的地址
tHead = temp;
}
}
bool CListTest::insertNode(int location, int value)
{
pNode p = Head;
int len = getLength();
if (location > len || location < 0) {
std::cout << "Error:insert location is woring!" << std::endl;
return false;
}
while (p && location) {
p = p->next;
location--;
}
pNode temp = new Node;
//std::cout << "insert add:" << temp<<std::endl;
temp->value = value;
temp->next = p->next;
p->next = temp;
return true;
}
bool CListTest::deleteNode(int location)
{
int len = getLength();
//不能删除头指针
if (location > len || location <= 0) {
std::cout << "Error:insert location is woring!" << std::endl;
return false;
}
pNode p = Head;
location--;
//定位到待删除节点前一个
while (p && location) {
p = p->next;
location--;
}
pNode pDel = p->next;//待删除节点
p->next = pDel->next;
delete pDel;
return true;
}
int CListTest::getLength()
{
pNode p = Head->next;
int len = 0;
while (p) {
len++;
p = p->next;
}
return len;
}
void CListTest::printList()
{
pNode p = Head->next;
while (p) {
std::cout << p->value << " --> ";
p = p->next;
}
std::cout << std::endl;
}