数据结构,实现线性表顺序存储(数据类型为int类型或char类型), 创建文件exp1-1-1.cpp随机输入5个字符(或对于给定的5个字符a,b,c,d,e),创建顺序表;求长度;获取第3个元素的值;在第4个元素前插入元素g,删除第5个元素,销毁创建的线性表,显示完整代码
时间: 2024-10-07 18:06:55 浏览: 34
要实现线性表顺序存储,你可以使用C++来完成。这里是一个简单的示例,用于创建顺序表并执行相应的操作:
```cpp
#include <iostream>
#include <string>
using namespace std;
// 定义顺序表节点结构体
struct Node {
char data;
Node* next;
};
class LinkedList {
private:
Node* head;
int length;
public:
LinkedList() : head(nullptr), length(0) {}
// 插入元素到链表末尾
void insertAtEnd(char value) {
Node* newNode = new Node();
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
length++;
}
// 获取链表长度
int getLength() {
return length;
}
// 获取指定位置的元素
char getElement(int index) {
if (index >= 0 && index < length) {
Node* temp = head;
for (int i = 0; i < index; i++) {
temp = temp->next;
}
return temp->data;
} else {
throw out_of_range("Index out of range");
}
}
// 在指定位置插入元素
void insertBeforeElement(int index, char value) {
if (index > 0 && index <= length) {
Node* newNode = new Node();
newNode->data = value;
if (index == 1) {
newNode->next = head;
head = newNode;
} else {
Node* temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
}
length++;
} else {
cerr << "Invalid insertion index" << endl;
}
}
// 删除指定位置的元素
void deleteElement(int index) {
if (index >= 0 && index < length) {
if (index == 0) {
Node* temp = head;
head = head->next;
delete temp;
} else {
Node* temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp->next;
}
Node* toDelete = temp->next;
temp->next = toDelete->next;
delete toDelete;
}
length--;
} else {
cerr << "Invalid deletion index" << endl;
}
}
~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
}
};
int main() {
LinkedList list;
string input;
cout << "Enter 5 characters: ";
cin >> input;
for (char c : input) {
list.insertAtEnd(c);
}
cout << "Sequence List Length: " << list.getLength() << endl;
cout << "Third element: " << list.getElement(2) << endl;
list.insertBeforeElement(3, 'g');
list.deleteElement(input.size());
return 0;
}
```
这段代码首先定义了一个顺序表的节点结构和链表类,包含了插入、获取长度、获取元素、插入和删除元素的方法。在`main`函数中,用户可以输入五个字符,程序会按照这些字符创建顺序表并执行所需的操作。
阅读全文