任务描述 本关任务:编写一个能将链表创建与排序的小程序。 编程要求 假设链表节点的结构体声明如下 struct node { int i; char c; node *next; }; 用户先依次输入每个节点的内容,要求输入的i要大于0 直到输入-1为止 按照i字段对链表所有元素进行由小到大排序并输出 效果如下: 输入: 12 a 14 c 10 b -1 输出: [10,b];[12,a]; [14,c] 开始你的任务吧,祝你成功!
时间: 2024-01-06 15:03:38 浏览: 119
下面是一个可能的实现,包含节点的创建、排序和输出。
```
#include <iostream>
using namespace std;
struct node {
int i;
char c;
node *next;
};
int main() {
node *head = nullptr;
node *tail = nullptr;
int i = 0;
char c;
// 输入节点内容,创建链表
while (true) {
cout << "请输入节点内容(i c),输入-1结束:";
cin >> i;
if (i == -1) break;
cin >> c;
if (i <= 0) {
cout << "i必须大于0!" << endl;
continue;
}
node *new_node = new node {i, c, nullptr};
if (head == nullptr) head = new_node;
if (tail != nullptr) tail->next = new_node;
tail = new_node;
}
// 链表排序
bool sorted = false;
while (!sorted) {
sorted = true;
node *prev = nullptr;
node *curr = head;
node *next = curr->next;
while (next != nullptr) {
if (curr->i > next->i) {
sorted = false;
if (prev != nullptr) prev->next = next;
else head = next;
curr->next = next->next;
next->next = curr;
prev = next;
next = curr->next;
} else {
prev = curr;
curr = next;
next = next->next;
}
}
}
// 输出链表
node *curr = head;
while (curr != nullptr) {
cout << "[" << curr->i << "," << curr->c << "]";
if (curr->next != nullptr) cout << ";";
curr = curr->next;
}
cout << endl;
// 释放链表内存
curr = head;
while (curr != nullptr) {
node *temp = curr;
curr = curr->next;
delete temp;
}
return 0;
}
```
注意在输入节点内容时,需要检查i是否大于0;在排序时,需要使用链表的插入操作来交换相邻节点的位置。
阅读全文