devc++c语言,实现单链表的基础操作,并用菜单显示
时间: 2024-12-12 14:31:13 浏览: 5
用C语言实现单链表的各种操作(一)
Dev-C++是一款常用的C/C++集成开发环境,它可以帮助程序员编写和调试C语言程序。在Dev-C++中,我们可以创建并实现单链表的基本操作,包括创建链表、插入节点、删除节点以及打印链表等。
**基础单链表操作示例**:
```cpp
#include <iostream>
using namespace std;
// 定义链表结构体
struct Node {
int data;
Node* next;
};
// 创建新节点
Node* createNode(int value) {
Node* newNode = new Node();
if (newNode != nullptr) {
newNode->data = value;
newNode->next = nullptr;
}
return newNode;
}
// 插入节点到链表头部
void insertAtStart(Node** head, int value) {
Node* newNode = createNode(value);
if (newNode != nullptr) {
newNode->next = *head;
*head = newNode;
}
}
// 插入节点到链表尾部
void append(Node** head, int value) {
Node* newNode = createNode(value);
if (newNode == nullptr || *head == nullptr) {
*head = newNode;
return;
}
Node* temp = *head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
// 删除指定值的节点
void deleteNode(Node** head, int value) {
if (*head == nullptr) {
return;
}
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;
}
}
// 打印链表
void printList(Node* node) {
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
int main() {
Node* head = nullptr; // 初始化链表为空
// 显示菜单选项
cout << "请选择操作:\n";
cout << "1. 创建链表\n";
cout << "2. 插入节点(开始)\n";
cout << "3. 插入节点(尾部)\n";
cout << "4. 删除节点\n";
cout << "5. 打印链表\n";
cout << "6. 退出\n";
// 循环处理用户输入
while (true) {
int choice;
cin >> choice;
switch (choice) {
case 1:
head = createNode(0); // 添加默认头结点
break;
case 2:
int value;
cin >> value;
insertAtStart(&head, value);
break;
case 3:
cin >> value;
append(&head, value);
break;
case 4:
int valueToDelete;
cin >> valueToDelete;
deleteNode(&head, valueToDelete);
break;
case 5:
printList(head);
break;
case 6:
exit(0); // 退出程序
break;
default:
cout << "无效选择,请重新输入。\n";
break;
}
}
return 0;
}
```
阅读全文