利用C++编写一个完整可运行的代码1.键盘输入一组元素,建立一个带头结点的单向链表(无序)。 2.遍历该单向链表。 3.把单向链表中元素逆置(不允许申请新的结点空间)。 4.在单向链表中删除所有的偶数元素结点。
时间: 2024-12-21 14:30:22 浏览: 2
以下是一个简单的C++代码示例,用于满足上述要求:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构
struct Node {
int data;
Node* next;
};
// 创建新节点
Node* createNode(int val) {
Node* newNode = new Node();
if (newNode == nullptr) {
cout << "Memory allocation failed!" << endl;
return nullptr;
}
newNode->data = val;
newNode->next = nullptr;
return newNode;
}
// 添加元素到链表末尾
void append(Node** head, int val) {
if (*head == nullptr) {
*head = createNode(val);
} else {
Node* curr = *head;
while (curr->next != nullptr) {
curr = curr->next;
}
curr->next = createNode(val);
}
}
// 遍历链表并打印元素
void printList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
// 逆置链表
void reverseList(Node** head) {
Node* prev = nullptr;
Node* curr = *head;
Node* nextTemp = nullptr;
while (curr != nullptr) {
nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
*head = prev;
}
// 删除偶数节点
void deleteEvenNodes(Node** head) {
Node* curr = *head;
while (curr != nullptr) {
if (curr->data % 2 == 0) {
Node* temp = curr;
curr = curr->next;
delete temp;
} else {
curr = curr->next;
}
}
}
int main() {
Node* head = nullptr;
// 输入元素并添加到链表
int n;
cout << "Enter the number of elements: ";
cin >> n;
for (int i = 0; i < n; ++i) {
int val;
cout << "Element " << i+1 << ": ";
cin >> val;
append(&head, val);
}
// 打印原链表
cout << "Original list: ";
printList(head);
// 逆置链表
reverseList(&head);
cout << "Reversed list: ";
printList(head);
// 删除偶数节点
deleteEvenNodes(&head);
cout << "List after deleting even numbers: ";
printList(head);
return 0;
}
```
阅读全文