(部分借助ChatGPT,因为笔试不需要那么精确,故没有每一个都敲)
1.合并——》排序——》去重
#include <stdio.h>
#define MAX_SIZE 100
int mergeAndSort(int a[], int aSize, int b[], int bSize) {
int merged[MAX_SIZE];
int c[MAX_SIZE];
int mergedSize = 0;
// 合并数组a和数组b到merged中
for (int i = 0; i < aSize; i++) {
merged[mergedSize++] = a[i];
}
for (int i = 0; i < bSize; i++) {
merged[mergedSize++] = b[i];
}
// 对merged进行递减排序
for (int i = 0; i < mergedSize - 1; i++) {
for (int j = i + 1; j < mergedSize; j++) {
if (merged[i] < merged[j]) {
int temp = merged[i];
merged[i] = merged[j];
merged[j] = temp;
}
}
}
// 去除重复元素放入数组c中
int cSize = 0;
for (int i = 0; i < mergedSize; i++) {
int isDuplicate = 0;
for (int j = 0; j < cSize; j++) {
if (merged[i] == c[j]) {
isDuplicate = 1;
break;
}
}
if (!isDuplicate) {
c[cSize++] = merged[i];
}
}
return cSize;
}
int main() {
int a[] = {3, 1, 5, 2, 3};
int aSize = 5;
int b[] = {7, 3, 6, 2, 5};
int bSize = 5;
int result = mergeAndSort(a, aSize, b, bSize);
printf("The number of elements in the final array is: %d\n", result);
return 0;
}
2.递归 出口为n<=m 共三种情况
#include <stdio.h>
int floor(int n, int m){
if(n<m)
return 1;
else if(n*5/13<m)
return 1+floor(n-n*5/13,m);
else
return 1+floor(n*5/13,m)+floor(n-n*5/13,m);
}
int main(){
int n=12, m=5;
int count=floor(n,m);
printf("%d",count);
return 0;
}
3.每插一次就比较,找到插入位置,需要注意若需插在头节点前需要更换头节点。(当然,可以创建个虚拟头节点dummy和头节点head进行统一化插入排序)
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 插入节点到有序链表中(降序)
void insertDescending(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL || data > (*head)->data) {
newNode->next = *head;
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL && current->next->data > data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// 打印链表
void printLinkedList(struct Node* head) {
struct Node* current = head;
printf("链表内容为: ");
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
int num;
printf("请输入任意正整数(以0结尾):\n");
scanf("%d", &num);
while (num != 0) {
insertDescending(&head, num);
scanf("%d", &num);
}
// 打印链表
printLinkedList(head);
return 0;
}