C++链表

本文介绍了使用C++实现链表的基本操作,包括插入节点、删除节点、获取指定位置节点值以及输出链表。示例代码展示了如何创建链表、在特定节点前插入新节点、删除指定节点以及遍历打印链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在复习数据结构和算法方面知识,链表是第一次学习的数据结构,虽然简单但写起来还是挺麻烦的。上代码:
#pragma once
#include<iostream>
using namespace std;
//单个节点
template<class Elem> class Node
{
public:
	Elem data;
	Node<Elem> *next;
	Node(const Elem& node,Node *nextNode = NULL)
	{
		data = node;
		next = nextNode;
	}
	Node(Node *nextNode = NULL) {next = nextNode;}
};

template<class  Elem> class LinkedList
{
public:
	LinkedList() { head = NULL; }
	//插入结点,把结点插入到exitData之前
	//1.链表为空,则插入结点为头结点
	//2.1.existData不存在,则插入到最后
	//3.existData存在
	//3.1.existData为头结点
	//3.2.existData为中间结点
	void insertList(const Elem& existData,const Elem& insertData) 
	{
		Node<Elem> *tempHead,*preNode,*newNode;
		tempHead = head;
		newNode = new Node<Elem>(insertData);
		if (head == NULL)
		{
			head = newNode;
		}
		else if(tempHead->data == existData) //头结点为existData
		{
			newNode->next = tempHead;
			head = newNode;
		}
		else //头结点为中间结点
		{
			while (tempHead != NULL)
			{
				preNode = tempHead;
				//存在则插入到existData前面并返回
				if (tempHead->data == existData)
				{
					preNode->next = newNode;
					newNode->next = tempHead;
					return ;
				}
				tempHead = tempHead->next;
			}
			//运行到这里说明不存在existData,则插到最后
			preNode->next = newNode;
			newNode->next = NULL;
		}
	}

	//删除existData结点
	//1.链表为空,直接返回
	//2.existData为头结点
	//3.existData为除头结点之外结点
	//4.existData不存在
	bool deleteList(const Elem& existData) 
	{
		Node<Elem> *tempHead,preNode;
		tempHead = head;
		if (tempHead == NULL)
		{
			return false;
		}

		if (tempHead->data == existData) //删除头结点
		{
			head = NULL;
			delete tempHead;
		}
		else
		{
			while (tempHead != NULL)
			{
				preNode = tempHead;
				if (tempHead->data == existData)
				{
					preNode.next = tempHead->next;
					delete tempHead;
				}
				tempHead = tempHead->next;
			}
		}
		return true;
	}

	//得到链表中第几个数的值
	Elem getNElem(int i)
	{
		Node<Elem> *tempHead = head;
		int count = 1;
		while (tempHead != NULL)
		{
			if (count == i)
			{
				return tempHead->data;
			}
			count++;
			tempHead = tempHead->next;
		}
		return -1;
	}

	void outputList()
	{
		Node<Elem> *temp = head;
		while (temp != NULL)
		{
			cout<<temp->data<<'\t';
			temp = temp->next;
		}
		cout<<endl;
	}
private:
	Node<Elem> *head;
};

int main()
{
	int n;
	cout<<"Input the length of the linkedlist:";
	cin>>n;
	LinkedList<int> linkedList;
	for (int i = 0;i < n;i++)
	{
		linkedList.insertList(i,i);
	}
	linkedList.outputList();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值