使用结构体和指针存储线性表结构,实现线性表的以 下操作:求链表节点总数、添加新节点、输出所有节点、任意位置插入新节点、删除节 点、查找节点。
时间: 2024-09-26 10:07:22 浏览: 43
在使用结构体和指针来存储线性表时,首先定义一个结构体表示链表节点,通常包含数据域和指向下一个节点的指针。以下是实现基本操作的步骤:
1. **定义链表节点结构** (Node.h):
```cpp
struct Node {
int data;
Node* next;
};
```
2. **初始化操作** - 求节点总数:
```cpp
int countNodes(Node* head) {
int count = 0;
if (head != nullptr) {
while (head) {
count++;
head = head->next;
}
}
return count;
}
```
3. **添加新节点** - 使用`push_back`方法(例如在C++里):
```cpp
void addNode(int value, Node*& head) {
Node* newNode = new Node{value, nullptr};
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
```
4. **输出所有节点**:
```cpp
void printList(Node* head) {
if (head != nullptr) {
Node* temp = head;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
std::cout << "\n";
}
}
```
5. **任意位置插入新节点**:
```cpp
void insertAtPosition(int value, int position, Node*& head) {
Node* newNode = new Node{value, nullptr};
if (position <= 0) {
newNode->next = head;
head = newNode;
} else {
Node* current = head;
for (int i = 1; i < position && current != nullptr; ++i) {
current = current->next;
}
if (current != nullptr) {
newNode->next = current->next;
current->next = newNode;
}
}
}
```
6. **删除节点** - 删除指定值的节点:
```cpp
void removeNode(int value, Node*& head) {
if (head != nullptr) {
if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* current = head;
while (current->next != nullptr && current->next->data != value) {
current = current->next;
}
if (current->next != nullptr) {
Node* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
}
}
}
```
7. **查找节点** - 查找特定值的节点:
```cpp
Node* findNode(int value, Node* head) {
Node* current = head;
while (current != nullptr) {
if (current->data == value) {
return current;
}
current = current->next;
}
return nullptr;
}
```
阅读全文