C++链表插入删除遍历实现

 本文通过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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值