文章目录
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.

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;
}
}

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

被折叠的 条评论
为什么被折叠?



