Description 输入n个数,要求程序按输入时的顺序建一单链表。 现在请你反转链表,并输出反转后的链表。 已知整数不超过100个,保证每个数不大于32767。 Input 第一行为n; 第二行有n个数。 Output 把这n个数逆序输出。
时间: 2024-04-09 17:27:41 浏览: 89
根据您的描述,以下是一个C++程序的示例,用于按输入顺序构建链表并反转链表,然后输出反转后的链表:
```cpp
#include <iostream>
using namespace std;
// 定义链表节点结构
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 添加节点到链表头部
void addNode(ListNode* &head, int val) {
ListNode* newNode = new ListNode(val);
if (head == nullptr) {
head = newNode;
} else {
newNode->next = head;
head = newNode;
}
}
// 反转链表
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* nextNode = curr->next;
curr->next = prev;
prev = curr;
curr = nextNode;
}
return prev;
}
// 输出链表
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != nullptr) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
int n;
cin >> n;
ListNode* head = nullptr;
for (int i = 0; i < n; i++) {
int val;
cin >> val;
addNode(head, val);
}
// 反转链表
head = reverseList(head);
// 输出反转后的链表
printList(head);
return 0;
}
```
您可以将上述代码保存为一个.cpp文件,然后使用C++编译器进行编译和运行。程序会先读取输入的n,然后读取n个数,构建链表。接着,程序会反转链表,并输出反转后的链表。
希望对您有所帮助!如果还有其他问题,请随时提问。
阅读全文
相关推荐













