LinkedList单向链表的C++实现

本文详细介绍了单向链表的实现与操作,包括插入、删除、查找、反转、检测环等关键功能。通过实例展示了如何在CLinkedList类中实现这些操作,适合初学者和进阶者深入理解链表数据结构。

1_Linked List

Singly linked lists are a type of a linked list where each node points to the next node in the sequence. It does not have any pointer that points to the previous node. That means we can traverse the list only in forward direction.

image-20210722155355425

1.0_list.h

头文件中包含节点结构体类型的定义和单向链表类的定义。

#ifndef LIST_H
#define LIST_H
struct Node {
	int data;
	Node *next;
};
typedef Node* NodePtr;
class CLinkedList {
private:
	NodePtr head;
public:
	CLinkedList();
	void insertAtFront(int value);
	void insertAtBack(int value);
	void insertAfter(int key, int value);
	int topFront();
	int topBack();
	int popFront();
	int popBack();
	void remove(int key);
	void print();
	bool isEmpty();
	bool find(int key);
	void reverse();
	bool hasCycle();
	void mergeTwoLists();
	void removeNthFromEnd(int N);
	NodePtr middleNode();
	//206,141,21,19,876 in Leetcode
};
#endif

1.1_CLinkedList

构造函数:用于创建一个新的链表,其中无内容,头节点指向空指针。

CLinkedList::CLinkedList() {
	head = nullptr;
}

1.2_insertAtFront

在链表的最前面插入节点。该过程可以分为三个步骤。

  • 创建新的节点,将数据存入该节点的数据区;

  • 新的节点的next指针指向原来的头节点;

  • 将新的节点作为原来的头节点。

时间复杂度和空间复杂度均为O(1)

//Insert value at the front of the list
void CLinkedList::insertAtFront(int value) {
	NodePtr node = new Node;
	node->data = value;
	node->next = nullptr;
	if (isEmpty()) {
		head = node;
	}
	else {
		node->next = head;
		head = node;
	}
}

1.3_insertAtBack

在链表的末尾插入节点。该过程可以分为三个步骤。

  • 创建新的节点,将数据存入该节点的数据区。

  • 创建一个节点用于循环,让该节点走到链表末端。

  • 让该节点的next指针指向新创建的节点。

时间复杂度为O(n),空间复杂度为O(1)

//Insert value at the back of the list
void CLinkedList::insertAtBack(int value) {
	NodePtr node = new Node;
	node->data = value;
	node->next = nullptr;
	if (isEmpty()) {
		head = node;
	}
	else {
		NodePtr currPtr = head;
		while (currPtr->next != nullptr) {
			currPtr = currPtr->next;
		}
		currPtr->next = node;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值