#include <stdio.h>
#define MAX_SIZE 10
typedef struct SqList {
int data[MAX_SIZE];
int length;
} SqList;
void ListPrint(SqList L);
void ListDelete(SqList *L);
void ListDelete_(SqList *L);
int main() {
SqList L;
while (scanf("%d", &L.length) && L.length!= 0) {
for (int i = 0; i < L.length; i++) {
scanf("%d", &(L.data[i]));
}
ListDelete(&L);
/*ListDelete_(&L);*/
ListPrint(L);
}
printf("error");
return 0;
}
void ListPrint(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d%c", L.data[i], (i == L.length - 1) ? 10 : 32);
}
}
/*对有序表和无序表都适用*/
void ListDelete(SqList *L) {
for (int i = 0; i < L->length; i++) {
int same = 0;//重复元素的个数
/*将当前元素与后面的所有元素进行比较*/
for (int j = i + 1; j < L->length; j++) {
if (L->data[i] == L->data[j]) {
same++;
} else {
L->data[j - same] = L->data[j];
}
}
L->length -= same;
}
}
/*只能处理有序表*/
void ListDelete_(SqList *L) {
int slow = 0, fast = 0;
while (fast < L->length) {
while (L->data[fast] == L->data[fast + 1]) {
fast++;
}
L->data[slow++] = L->data[fast++];
}
L->length = slow;
}
7.将两个有序顺序表合并为一个新的有序顺序表。
输入样例:
3 4
1 3 5
2 4 6 8
0 0
输出样例:
1 2 3 4 5 6 8
#include <stdio.h>
#define MAX_SIZE 10
typedef struct SqList {
int data[MAX_SIZE];
int length;
} SqList;
void ListPrint(SqList L);
void ListMerge(SqList A, SqList B, SqList *L);
int main() {
SqList A;
SqList B;
while (scanf("%d %d", &A.length, &B.length) && A.length != 0 && B.length != 0) {
SqList L;
L.length = 0;
for (int i = 0; i < A.length; i++) {
scanf("%d", &(A.data[i]));
}
for (int i = 0; i < B.length; i++) {
scanf("%d", &(B.data[i]));
}
ListMerge(A, B, &L);
ListPrint(L);
}
return 0;
}
void ListPrint(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d%c", L.data[i], (i == L.length - 1) ? 10 : 32);
}
}
void ListMerge(SqList A, SqList B, SqList *L) {
int cur_a = 0, cur_b = 0, cursor = 0;
while (cur_a < A.length && cur_b < B.length) {
if (A.data[cur_a] < B.data[cur_b]) {
L->data[cursor++] = A.data[cur_a++];
L->length++;
} else {
L->data[cursor++] = B.data[cur_b++];
L->length++;
}
}
while (cur_a < A.length) {
L->data[cursor++] = A.data[cur_a++];
L->length++;
}
while (cur_b < B.length) {
L->data[cursor++] = B.data[cur_b++];
L->length++;
}
}
8.已知在一维数组A[m+n]中依次存放两个线性表
(
a
1
,
a
2
,
a
3
,
…
a
m
)
(a_1, a_2, a_3, \dots a_m)
(a1,a2,a3,…am)和
(
b
1
,
b
2
,
b
3
,
…
b
n
)
(b_1, b_2, b_3, \dots b_n)
(b1,b2,b3,…bn)。试编写一个函数,将数组中两个顺序表的位置互换,即将
(
b
1
,
b
2
,
b
3
,
…
b
n
)
(b_1, b_2, b_3, \dots b_n)
(b1,b2,b3,…bn)放在
(
a
1
,
a
2
,
a
3
,
…
a
m
)
(a_1, a_2, a_3, \dots a_m)
(a1,a2,a3,…am)前面。