C++面向对象方式建立链表以及相关操作

最近在看b站上一个视频,学习数据结构,了解链表后发现所有的视频都不是面向对象方式,然后就好奇,面向对象应该如何实现链表,是否会更方便。于是自己动手试了一下,发现可以将链表的一系列操作封装,便以使用。

1.运行结果

 1)首先插入6个元素

 2)删除结点

 3)打印删除后的链表

 4)反转链表

2.源码

#include<iostream>
using namespace std;
struct Node
{
	int data;
	Node* next;
};
class list
{
public:
	Node* head; //头节点地址
	int len;	//链表长度
public:
	list()
	{
		len = 0;
		head = new Node;
		head->next = NULL;
	}
	~list()
	{
		delete[]head;
	}
	void Insert(int n)
	{
		Node* head1 = head;
		Node* temp = new Node;
		temp->next = NULL;
		temp->data = n;
		len++;
		if (head->next == NULL)
		{
			head->next = temp;
			return;
		}
		while (head1->next != NULL)
		{
			head1 = head1->next;
		}
		head1->next = temp;
	}
	void Print()
	{
		cout << "共有" << len << "个结点\t";
		Node* head1 = NULL;
		head1 = head->next;
		while (head1 != NULL)
		{
			cout << head1->data << " ";
			head1 = head1->next;
		}
		cout << endl;
	}
	void Delete()
	{
		int n = 0;
		while (n <= 0 || n > len)
		{
			cout << "删除第几个元素?";
			cin >> n;
		}
		Node* head1 = head;
		for (int i = 0; i < n - 1; i++)
		{
			head1 = head1->next;
		}
		Node* temp = head1->next;
		head1->next = temp->next;
		delete temp;
		len--;
	}
	void Reverse()
	{
		if (head->next == NULL || head->next->next == NULL)
		{
			return;
		}
		Node* t = NULL;
		Node* p = head->next;
		Node* q = p->next;
		while (q != NULL)
		{
			t = q->next;
			q->next = p;
			p = q;
			q = t;
		}
		head->next->next = NULL;
		head->next = p;
	}
};

int main()
{
	list list1;
	list1.Insert(1);
	list1.Insert(2);
	list1.Insert(3);
	list1.Insert(4);
	list1.Insert(5);
	list1.Insert(6);
	list1.Print();	
	list1.Delete();	
	list1.Print();	
	list1.Reverse();	
	list1.Print();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值