c++解决1)实现链表的排序(升序) 2)实现两个有序链表的合并:A=AUB,要求合并后仍然有序。 提交前请将所有的提示信息去掉,只保留最后的输出结果。例如运行时:从键盘直接输入: 212 3123 输出结果为: 1 2 3 分别表示第一个链表元素个数为2,元素分别为1.2;第二个链表元素个数为3,元素分别为1.2,3.
时间: 2024-02-25 22:54:32 浏览: 69
设计算法合并非递减有序链表
5星 · 资源好评率100%
好的,我可以帮你解决这两个问题。首先是链表的排序,可以使用冒泡排序或者快速排序等算法。以下是使用冒泡排序的示例代码:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* sortList(ListNode* head) {
ListNode *p, *q, *tail = NULL;
do {
p = head;
q = p->next;
head = q;
while (q) {
if (p->val > q->val) {
p->next = q->next;
q->next = p;
if (head == q) head = p;
if (tail == p) tail = q;
p = q;
} else {
p = p->next;
}
q = p->next;
}
tail = p;
} while (head != tail);
return head;
}
int main() {
int n, val;
cin >> n;
ListNode *head = NULL, *p = NULL;
for (int i = 0; i < n; i++) {
cin >> val;
ListNode *node = new ListNode(val);
if (p == NULL) {
p = head = node;
} else {
p->next = node;
p = node;
}
}
head = sortList(head);
while (head) {
cout << head->val << " ";
head = head->next;
}
return 0;
}
```
接下来是两个有序链表的合并,可以使用双指针法。以下是示例代码:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head = NULL, *p = NULL;
while (l1 && l2) {
ListNode *node;
if (l1->val < l2->val) {
node = new ListNode(l1->val);
l1 = l1->next;
} else {
node = new ListNode(l2->val);
l2 = l2->next;
}
if (p == NULL) {
p = head = node;
} else {
p->next = node;
p = node;
}
}
if (l1) {
if (p == NULL) {
head = l1;
} else {
p->next = l1;
}
} else if (l2) {
if (p == NULL) {
head = l2;
} else {
p->next = l2;
}
}
return head;
}
int main() {
int n, m, val;
cin >> n;
ListNode *l1 = NULL, *p = NULL;
for (int i = 0; i < n; i++) {
cin >> val;
ListNode *node = new ListNode(val);
if (p == NULL) {
p = l1 = node;
} else {
p->next = node;
p = node;
}
}
cin >> m;
ListNode *l2 = NULL;
p = NULL;
for (int i = 0; i < m; i++) {
cin >> val;
ListNode *node = new ListNode(val);
if (p == NULL) {
p = l2 = node;
} else {
p->next = node;
p = node;
}
}
ListNode *head = mergeTwoLists(l1, l2);
while (head) {
cout << head->val << " ";
head = head->next;
}
return 0;
}
```
希望能帮到你!
阅读全文