C++链表

C++链表,第1张

C++链表
#pragma once
#include 
using namespace std;

typedef int DataType;
class DataNode
{
public:
	DataType data;
	DataNode* next;
};

class Datalink
{
private:
	DataNode* head;
	int linksize;
public:
	Datalink();
	virtual ~Datalink() { delete head; }
	DataNode* CreateNode();
	//增
	void AddNodeTolinkAtHead(DataNode* newnode);
	void AddNodeTolinkAtBack(DataNode* newnode);
	//删
	void DelNode(DataType data);
	//改
	void ModNode(DataType data,DataType newdata);
	//查
	int FindData(DataType data);
	//反转
	void Revlink();
	//连接
	void Con2link(Datalink* newNode);
	//看
	void Showlink();
};


#include "Datalink.h"

Datalink::Datalink()
{
	head = new DataNode;
	head->data = 0;
	head->next = NULL;
	linksize = 0;
}

DataNode* Datalink::CreateNode()
{
	DataNode* node = new DataNode;
	cout << "请输入节点的值:";
	cin >> node->data;
	node->next = NULL;
	return node;
}

void Datalink::AddNodeTolinkAtHead(DataNode* newnode)
{
	if (linksize == 0)
	{
		head = newnode;
		linksize++;
		return;
	}
	newnode->next = head;
	head = newnode;
	linksize++;
}

void Datalink::AddNodeTolinkAtBack(DataNode* newnode)
{
	if (linksize == 0)
	{
		head = newnode;
		linksize++;
		return;
	}
	DataNode* pNode = head;
	while (pNode->next != NULL)
		pNode = pNode->next;
	pNode->next = newnode;
	linksize++;
}

void Datalink::DelNode(DataType data)
{
	DataNode* pnode = head;
	int cursize = linksize;
	for (int i = 0; i < cursize; i++)
	{
		if (pnode->next == NULL)
			return;
		if (pnode->next->data == data)
		{
			pnode->next = pnode->next->next;
			linksize--;
		}
		else
			pnode = pnode->next;
	}
}

void Datalink::ModNode(DataType data, DataType newdata)
{
	DataNode* pnode = head;
	for (int i = 0; i < linksize; i++)
	{
		if (pnode->data == data)
			pnode->data = newdata;
		pnode = pnode->next;
	}
}

int Datalink::FindData(DataType data)
{
	DataNode* pnode = head;
	int cnt = 0;
	for (int i = 0; i < linksize; i++)
	{
		if (pnode->data == data)
			cnt++;
		pnode = pnode->next;
	}
	return cnt;
}

void Datalink::Revlink()
{
	DataNode* nextNode = NULL;
	DataNode* curNode = head;
	DataNode* preNode = NULL;
	for (int i = 0; i < linksize; i++)
	{
		nextNode = curNode->next;
		curNode->next = preNode;
		preNode = curNode;
		curNode = nextNode;
	}
	head = preNode;
}

void Datalink::Con2link(Datalink* newhead)
{
	DataNode* pNode = head;
	while (pNode->next)
		pNode = pNode->next;
	pNode->next = newhead->head;
	linksize += newhead->linksize;
}

void Datalink::Showlink()
{
	DataNode* pNode = head;
	for (int i = 0; i < linksize; i++)
	{
		cout << "节点->" << i;
		cout << "->值->" << pNode->data << endl;
		pNode = pNode->next;
	}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5635173.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存