用c++语言写出内链表实现线性表的初始化、插入、删除、求表长、查找、打印线性表等操作。
时间: 2024-10-18 19:10:52 浏览: 34
用链表实现的线性表(以验证)
在C++中,我们可以使用结构体和指针来实现单向内部链接列表(Internal Link List)。首先,定义一个节点结构:
```cpp
#include <iostream>
struct Node {
int data;
Node* next; // 指向下一个节点的指针
Node(int value = 0) : data(value), next(nullptr) {}
};
```
接下来,我们实现一些基本操作:
1. **初始化** (创建空链表):
```cpp
Node* createList() {
return nullptr;
}
```
2. **插入**:
```cpp
void insertAtEnd(Node*& head, int value) {
if (!head) {
head = new Node(value);
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = new Node(value);
}
}
```
3. **删除** (删除指定值的节点,这里仅示例删除尾部节点,其他位置需要额外处理):
```cpp
void deleteLast(Node*& head, int value) {
if (head && head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* prev = head;
Node* current = head->next;
while (current && current->data != value) {
prev = current;
current = current->next;
}
if (current) {
prev->next = current->next;
delete current;
}
}
```
4. **求表长**:
```cpp
int length(Node* head) {
int count = 0;
while (head) {
++count;
head = head->next;
}
return count;
}
```
5. **查找**:
```cpp
Node* find(Node* head, int value) {
Node* current = head;
while (current && current->data != value) {
current = current->next;
}
return current;
}
```
6. **打印线性表** (顺序遍历并打印节点值):
```cpp
void printList(Node* head) {
if (head) {
Node* temp = head;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << std::endl;
} else {
std::cout << "Empty list." << std::endl;
}
}
```
阅读全文