dev c++设计一个单链表的基本操作的演示程序 要求实现下列五种基本运算:(1)初始化单链表(2)生成单链表(3)遍历单链表(4)在第i个元素前插入一个元素e(5)删除第i个元素(6)将单链表逆置
时间: 2024-11-09 19:19:06 浏览: 12
在Dev C++中创建一个单链表的基本操作演示程序,我们可以按照以下步骤编写:
```cpp
#include <iostream>
using namespace std;
// 定义单链表节点结构体
struct Node {
int data;
Node* next;
};
// 初始化空链表
Node* createList() {
return NULL;
}
// 创建单链表并添加元素
Node* insertElement(Node* head, int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->next = head;
return newNode;
}
// 遍历单链表
void traverseList(Node* head) {
if (head == NULL) {
cout << "链表为空" << endl;
return;
}
Node* current = head;
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
// 在第i个位置插入元素
Node* insertBeforeIndex(Node* head, int i, int e) {
if (i <= 0 || head == NULL) {
return head;
}
Node* newNode = new Node();
newNode->data = e;
Node* prev = head;
for (int j = 1; j < i && prev != NULL; ++j) {
prev = prev->next;
}
if (prev != NULL) {
newNode->next = prev->next;
prev->next = newNode;
} else {
cout << "插入位置超出链表范围" << endl;
}
return head;
}
// 删除第i个元素
Node* deleteElement(Node* head, int i) {
if (head == NULL || i <= 0) {
return head;
}
Node* temp = head;
Node* prev = NULL;
if (i == 1) {
head = head->next;
} else {
for (int j = 1; j < i && temp != NULL; ++j) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
cout << "删除位置超出链表范围" << endl;
return head;
}
prev->next = temp->next;
}
delete temp;
return head;
}
// 逆置单链表
Node* reverseList(Node* head) {
Node* prev = NULL;
Node* current = head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
int main() {
// 初始化一个空链表
Node* head = createList();
// 添加元素到链表
head = insertElement(head, 1);
head = insertElement(head, 2);
head = insertElement(head, 3);
// 遍历链表
cout << "原始链表: ";
traverseList(head);
// 插入元素示例
head = insertBeforeIndex(head, 2, 4);
cout << "\n插入4后链表: ";
traverseList(head);
// 删除元素示例
head = deleteElement(head, 2);
cout << "\n删除2后链表: ";
traverseList(head);
// 逆置链表
head = reverseList(head);
cout << "\n逆置后的链表: ";
traverseList(head);
return 0;
}
```
运行这个程序,你会看到不同的链表操作效果。注意这里的索引从1开始计数。
阅读全文