编写一个函数,合并两个带头结点的递增有序单链表,合并后的单链表保持递增有序性。函数原型为: Node* merge_sorted_lists(Node* head1, Node* head2),即合并单链表head1和单链表head2,返回合并后的单链表的头结点地址; 编写一个函数,实现对带头结点的单链表排序,排序算法为简单选择法,函数原型为: void List_sort(Node* head),即对单链表head进行排序; 结点数据定义为: struct Node { int data; struct Node* next; };
#include<stdio.h>
struct Node {
int data;
struct Node* next;
};
void List_sort(Node* head)
{
//先把数据读出来,然后把数据排序
//排完序之后再放回链表中
Node* current = head->next;
int array[1000] = {};
int i = 0;
while (current!=NULL)//读取
{
array[i++] = current->data;
current = current->next;
}
QuickSort(array, 0, i - 1);
current = head->next;
int j = 0;
while (current!=NULL)//写入
{
current->data = array[j++];
current = current->next;
}
return;
}
Node* merge_sorted_lists(Node* head1, Node* head2) {
Node dummy; // 创建一个哑节点,作为新链表的头部
Node* tail = &dummy; // tail用于指向新链表的最后一个节点
dummy.next = NULL;
Node* cur1 = head1->next; // 跳过头节点
Node* cur2 = head2->next; // 跳过头节点
while (cur1 != NULL && cur2 != NULL) {
if (cur1->data < cur2->data) {
tail->next = cur1;
cur1 = cur1->next;
}
else {
tail->next = cur2;
cur2 = cur2->next;
}
tail = tail->next;
}
// 将剩余部分接到新链表的尾部
if (cur1 != NULL) {
tail->next = cur1;
}
else if (cur2 != NULL) {
tail->next = cur2;
}
// 由于使用了哑节点,最终链表的头节点是dummy.next
head1->next = dummy.next; // 将合并后的链表接回head1的头节点
return head1; // 返回合并后的链表的头节点
}
up一开始没有用到链表原本有序的条件,迷信了一波快速排序,但结果是有一组15分的数据跑不完,一直time out
使用快速排序的代码如下:
#include<stdio.h>
struct Node {
int data;
struct Node* next;
};
void QuickSort(int array[], int left, int right)
{
if (left >= right) return;
int l = left, r = right;
while (1)
{
if (l == r) break;
while (1)
{
if (l == r) break;
if (array[l] > array[r])
{
int temp = array[l];
array[l] = array[r];
array[r] = temp;
l++;
break;
}
r--;
}
while (1)
{
if (l == r) break;
if (array[l] > array[r])
{
int temp = array[l];
array[l] = array[r];
array[r] = temp;
r--;
break;
}
l++;
}
}
QuickSort(array, left, l - 1);
QuickSort(array, r + 1, right);
}
void List_sort(Node* head)
{
//先把数据读出来,然后把数据排序
//排完序之后再放回链表中
Node* current = head->next;
int array[1000] = {};
int i = 0;
while (current!=NULL)//读取
{
array[i++] = current->data;
current = current->next;
}
QuickSort(array, 0, i - 1);
current = head->next;
int j = 0;
while (current!=NULL)//写入
{
current->data = array[j++];
current = current->next;
}
return;
}
Node* merge_sorted_lists(Node* head1, Node* head2)
{
Node* current=head1;
while (1)//current走到head1的尾部
{
if (!current->next) break;
current = current->next;
}
current->next = head2->next;
List_sort(head1);
return head1;
}