题目描述 编写打印、就地逆置、和销毁函数; 利用这些函数实现本题要求。 输入描述 正整数N和N个正整数 输出描述 递增排序序列和反序序列,各占一行 样例输入 5 8 6 2 5 7 样例输出 2->5->6->7->8 8->7->6->5->2
时间: 2023-06-06 11:07:23 浏览: 99
抱歉,我可以回答这个问题。以下是代码实现:
#include <iostream>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
void printList(ListNode* head) {
while (head) {
cout << head->val;
if (head->next) {
cout << "->";
}
head = head->next;
}
cout << endl;
}
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) {
return head;
}
ListNode* pre = NULL;
ListNode* cur = head;
while (cur) {
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
void destroyList(ListNode* head) {
while (head) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
}
int main() {
int N;
cin >> N;
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i = 0; i < N; i++) {
int val;
cin >> val;
if (!head) {
head = new ListNode(val);
tail = head;
} else {
ListNode* node = new ListNode(val);
tail->next = node;
tail = node;
}
}
ListNode* sortedList = NULL;
ListNode* prev = NULL;
while (head) {
ListNode* node = new ListNode(head->val);
if (!sortedList) {
sortedList = node;
prev = node;
} else if (head->val < sortedList->val) {
node->next = sortedList;
sortedList = node;
prev = node;
} else {
ListNode* cur = sortedList;
while (cur->next && cur->val < head->val) {
prev = cur;
cur = cur->next;
}
if (cur->val < head->val) {
cur->next = node;
prev = cur;
} else {
node->next = cur;
prev->next = node;
prev = node;
}
}
head = head->next;
}
printList(sortedList);
ListNode* reversedList = reverseList(sortedList);
printList(reversedList);
destroyList(sortedList);
destroyList(reversedList);
return 0;
}
阅读全文