输入10个数字,并根据这些数字构造单向链表,之后,再反转链表并打印输出,即A={a1,a2,…,a_n}反转成A={a_n,…,a2,a1} 输入提示: "Please input %d numbers:\n" 输入格式: "%d" 输出格式: "%5d"
时间: 2023-07-19 10:31:02 浏览: 51
好的,我可以帮您解决这个问题。以下是 C++ 代码实现:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
const int N = 10;
int nums[N];
cout << "Please input " << N << " numbers:" << endl;
for (int i = 0; i < N; i++) {
scanf("%d", &nums[i]);
}
ListNode* head = new ListNode(nums[0]);
ListNode* tail = head;
for (int i = 1; i < N; i++) {
ListNode* node = new ListNode(nums[i]);
tail->next = node;
tail = node;
}
head = reverseList(head);
cout << "After reverse:" << endl;
ListNode* p = head;
while (p != NULL) {
printf("%5d", p->val);
p = p->next;
}
cout << endl;
return 0;
}
```
输出结果:
```
Please input 10 numbers:
1 2 3 4 5 6 7 8 9 10
After reverse:
10 9 8 7 6 5 4 3 2 1
```