用c++编写定义一个指针L,指向表头结点,实现链表的初始化、插入、删除、定位查找、按值查找、输出、求表长、清空链表等操作。
时间: 2024-09-29 22:04:31 浏览: 36
在C++中,我们可以使用结构体或类定义链表节点,并通过指针L来管理链表。这里是一个简单的例子,首先定义链表节点:
```cpp
#include <iostream>
// 链表节点定义
struct Node {
int data;
Node* next; // 指向下一个节点的指针
};
```
然后定义链表类,包含初始化、插入、删除、查找、输出、求表长以及清空链表等基本操作:
```cpp
class LinkedList {
private:
Node* head; // 表头指针
public:
// 初始化链表为空
LinkedList() : head(nullptr) {}
// 插入元素到链表末尾
void insert(int value) {
Node* newNode = new Node{value, nullptr};
if (head == nullptr) {
head = newNode;
} else {
Node* curr = head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = newNode;
}
}
// 删除指定位置的节点
void remove(int value) {
if (head == nullptr) return;
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* curr = head;
while (curr->next != nullptr && curr->next->data != value) {
curr = curr->next;
}
if (curr->next != nullptr) {
Node* temp = curr->next;
curr->next = curr->next->next;
delete temp;
}
}
// 查找特定值的位置
int find(int value) {
Node* curr = head;
int index = 0;
while (curr != nullptr && curr->data != value) {
curr = curr->next;
index++;
}
return curr == nullptr ? -1 : index; // 返回-1表示未找到
}
// 输出链表元素
void display() {
Node* curr = head;
while (curr != nullptr) {
std::cout << curr->data << " ";
curr = curr->next;
}
std::cout << "\n";
}
// 计算链表长度
int length() {
int count = 0;
Node* curr = head;
while (curr != nullptr) {
count++;
curr = curr->next;
}
return count;
}
// 清空链表
void clear() {
if (head != nullptr) {
Node* temp = head;
head = nullptr;
while (temp != nullptr) {
Node* nextTemp = temp->next;
delete temp;
temp = nextTemp;
}
}
}
};
阅读全文