编写程序linklist.cpp,实现带头结点单链表的各种基本运算(假设单链表的元素类型为char),并在此基础上设计主程序main.cpp,完成如下功能:1.初始化单链表
时间: 2024-12-10 19:29:14 浏览: 62
在C++中,我们可以创建一个名为`LinkList`的类来表示带头节点的单链表,并包含插入、删除、查找等基本操作。首先,我们需要定义头节点结构体以及链表节点结构体:
```cpp
// 链表节点结构
struct Node {
char data;
Node* next;
};
// 头节点结构
struct ListNode {
char data;
Node* head;
ListNode(char val) : data(val), head(nullptr) {}
};
```
接下来,我们编写`LinkList.cpp`文件中的基本链表操作:
```cpp
#include "LinkList.h"
// 插入节点到链表头部
void insertAtBegin(ListNode*& list, char value) {
Node* newNode = new Node{value};
newNode->next = list;
list = newNode;
}
// 删除节点(仅删除第一个匹配值的节点)
bool deleteNode(ListNode*& list, char value) {
if (list == nullptr || list->data != value)
return false;
Node* temp = list;
list = list->next;
delete temp;
return true;
}
// 查找节点是否存在
bool searchListNode(const ListNode* list, char value) {
while (list != nullptr) {
if (list->data == value)
return true;
list = list->next;
}
return false;
}
// 显示链表内容
void printList(const ListNode* list) {
std::cout << "Chain List: ";
while (list != nullptr) {
std::cout << list->data << " -> ";
list = list->next;
}
std::cout << "NULL\n";
}
```
然后,在`main.cpp`中实现主程序,完成所需的功能:
```cpp
#include <iostream>
#include "LinkList.h"
int main() {
// 初始化链表
ListNode myList('A');
// 执行操作,例如插入、删除和打印
insertAtBegin(myList.head, 'B');
printList(myList.head); // 输出: Chain List: B -> A -> NULL
// 删除节点
deleteNode(myList.head, 'B');
printList(myList.head); // 输出: Chain List: A -> NULL
// 检查节点是否存在
if (searchListNode(myList.head, 'B')) {
std::cout << "Node 'B' found.\n";
} else {
std::cout << "Node 'B' not found.\n";
}
return 0;
}
```
这将创建一个简单的单链表,可以插入、删除节点,查找特定元素,并打印链表的内容。
阅读全文
相关推荐

















