C++单链表代码实现

C++的标准模板库(STL)提供了List容器,实质上它是一个双向循环链表,学习数据结构的过程中自己简单用c++写了单链表。

1、数据类型这里简单化设成了int,如果要实现其他数据类型可以写一个类模板Template<class T>就行了

2、遍历算法find从头遍历到尾,时间复杂度为O(N),但单链表也没有其他方法可用了,二分法之类的算法我觉得至少应当在双向链表中讨论

3、双向链表,已经链表的一些相关算法后续慢慢更新

代码如下:

class Single_List_Node{
public:
	Single_List_Node(int data, Single_List_Node *p)
	{
		this->m_Data = data;
		this->next = p;
	}
	int m_Data;
	Single_List_Node* next;
};

class Single_List {
public:
	Single_List()
	{
		this->m_Size = 0;
		this->head = NULL;
	}

	void Add(int data)
	{
		//空表的情况
		if (this->m_Size == 0 )
		{
			head = new Single_List_Node(data, NULL); //修改head指针让其指向第一个结点
			this->m_Size++;
			return;
		}
		//不为空表的情况,头插
			Single_List_Node* new_Node = new Single_List_Node(data, head);
			head = new_Node;
			this->m_Size++;
		
	}

	void Delete(Single_List_Node* p)
	{
		if (m_Size == 0 && this->head == head)
		{
			return;
		}
		//如果要删头结点
		if (p == this->head)
		{
			head = head->next;
			delete p;
			this->m_Size--;
			return;
		}
		//如果删其他位置的结点,找到待删结点的前一个结点的位置
		Single_List_Node *index = head;
		while (index->next != p)
		{
			index = index->next;
		}
		index->next = p->next;
		delete p;
		this->m_Size--;
	}

	void modify(Single_List_Node* p,int new_Data)
	{
		p->m_Data = new_Data;
	}

	Single_List_Node* find(int data)
	{
		Single_List_Node *index = head;
		while (index->m_Data !=data)
		{
			index = index->next;
		}
		return index;
	}
	void printList()
	{
		if (head == NULL)
		{
			cout << "链表为空";
		}
		Single_List_Node *p = head;
		while (p != NULL)
		{
			cout << p->m_Data << " ";
			p = p->next;
		}
		cout << endl;
	}
public:
	int m_Size;
	Single_List_Node* head;
};

后续学习过程中继续补充一些链表相关的代码。。

新手,不喜勿喷

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值