用C++建立一个线性表,要求有初始化,插入,删除,查找,销毁这5个基本操作,主函数要用switch函数让用户选择需要的操作,只能用cout进行输出和cin进行输入,给出的代码要有明显的缩进和解释
时间: 2024-06-05 21:06:30 浏览: 101
#include <iostream>
using namespace std;
//定义一个结构体表示线性表中的元素
struct Node {
int data;
Node* next;
};
//定义一个链表类
class LinkedList {
private:
Node* head; //链表头指针
public:
//初始化链表
LinkedList() {
head = new Node;
head->next = NULL;
}
//插入元素
void insert(int num) {
Node* p = head;
while (p->next != NULL) {
p = p->next;
}
Node* newNode = new Node;
newNode->data = num;
newNode->next = NULL;
p->next = newNode;
cout << "插入成功" << endl;
}
//删除元素
void remove(int num) {
Node* p = head->next;
Node* pre = head;
while (p != NULL) {
if (p->data == num) {
pre->next = p->next;
delete p;
cout << "删除成功" << endl;
return;
}
pre = p;
p = p->next;
}
cout << "没有找到要删除的元素" << endl;
}
//查找元素
void search(int num) {
Node* p = head->next;
while (p != NULL) {
if (p->data == num) {
cout << "找到了要查找的元素" << endl;
return;
}
p = p->next;
}
cout << "没有找到要查找的元素" << endl;
}
//销毁链表
void destroy() {
Node* p = head->next;
while (p != NULL) {
Node* temp = p;
p = p->next;
delete temp;
}
head->next = NULL;
cout << "销毁成功" << endl;
}
};
int main() {
LinkedList list;
int choice, num;
while (true) {
cout << "请选择操作:1.插入 2.删除 3.查找 4.销毁 5.退出" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "请输入要插入的元素:" << endl;
cin >> num;
list.insert(num);
break;
case 2:
cout << "请输入要删除的元素:" << endl;
cin >> num;
list.remove(num);
break;
case 3:
cout << "请输入要查找的元素:" << endl;
cin >> num;
list.search(num);
break;
case 4:
list.destroy();
break;
case 5:
return 0;
default:
cout << "输入错误,请重新选择操作" << endl;
break;
}
}
return 0;
}
阅读全文