合并有序链表
一、题目
二、代码
1. 思想:合并时分两步走,一,合并;二,去重。
因为不同子链可能有重复
2. 但是合并时去重就行了嘛?
递增数列的定义:对于一个数列,如果从数列的第2项起,每一项的值都--不小于--它前面的一项的值,则称这样的数列为递增数列。
按照两套定义有不同的结果,
首先对第一个定义进行解答,由于题干没有说明是严格递增子序列,则子链中存在重复的元素的情况,那么就得在合并的时候去重的同时额外给子链去重,
其次,就是第二种定义的解答,只需要考虑两个子链重复的情况,取其一就行。
下面对两种定义进行了解答。
三、我的解答
1.chat的说法
————如果是这样话,那么就非常简单了
list* merge(list* L1, list* L2) {
if (!L1 || !L2) return L1 ? L1 : L2;
list* p1 = L1->next, * p2 = L2->next, * p3 = L1;
while (p1 && p2) {
if (p1->value <= p2->value) {
p3->next = p1;
if (p1->value == p2->value)
p2 = p2->next;
p1 = p1->next;
}
else {
p3->next = p2;
p2 = p2->next;
}
p3 = p3->next;
}
p3->next = p1 ? p1 : p2;
free(L2);
return L1;
}
2.第二套解答
#include<stdio.h>
#include<malloc.h>
typedef struct linkList {
int value;
struct linkList* next;
}list;
void insert_tail(list* L, int data) {
if (L) {
list* p = L;
while (p->next)
p = p->next;
list* newNode = (list*)malloc(sizeof(list));
newNode->value = data;
newNode->next = p->next;
p->next = newNode;
}
}
list* init(list* L, int n) {
L = (list*)malloc(sizeof(list));
L->next = NULL;
int temp;
for (int i = 0; i < n; i++) {
scanf("%d", &temp);
insert_tail(L, temp);
}
return L;
}
void print(list* L) {
if (!L) return;
list* p = L->next;
while (p) {
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
//子链去重
list* deduplicate(list* L) {
list* p = L;
list* pos = p;
while (p) {
while (p && p->value == pos->value)
p = p->next;
if (p != pos)
pos->next = p;
pos = pos->next;
}
return L;
}
list* merge(list* L1, list* L2) {
if (!L1 || !L2) return L1 ? deduplicate(L1) : deduplicate(L2);
list* p1 = L1->next, * p2 = L2->next, * p3 = L1;
while (p1 && p2) {
int temp;
if (p1->value <= p2->value) {
temp = p1->value;
p3->next = p1;
p1 = p1->next;
}
else {
temp = p2->value;
p3->next = p2;
p2 = p2->next;
}
//去重
while (p1 && p1->value == temp)
p1 = p1->next;
while (p2 && p2->value == temp)
p2 = p2->next;
p3 = p3->next;
}
p3->next = p1 ? deduplicate(p1) : deduplicate(p2);
free(L2);
return L1;
}
int main() {
list* L1 = NULL;
L1 = init(L1, 5);
list* L2 = NULL;
L2 = init(L2, 5);
//合并
list* L3 = merge(L1, L2);
print(L3);
return 0;
}
————演示: