本帖最后由 jhq999 于 2022-12-20 15:39 编辑
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node *next;
};
typedef struct node *LIST;
LIST divide(LIST x, int p) ;
LIST merge(LIST x, LIST y) ;
int list_len(LIST x) {//リストの要素数を求める関数
if (x == NULL) return 0;
return 1 + list_len(x->next);
}
void list_show(char *m, LIST x) {//リストにある値を表示する関数
printf("%s:", m);
while (x != NULL) {
printf("%d ", x->val);
x = x->next;
}
printf("\n");
}
LIST add_top(LIST x, int v) {//リストxの先頭に、値vを繋げたリストを返す関数
LIST t;
t = (LIST) malloc(sizeof(struct node));
if (t == NULL) {
printf("malloc failed");
exit(-1);
}
t->val = v;
t->next = x;
return t;
}
int main(void) {
int i, len;
LIST list1 = NULL, list2, mix;
printf("length: ");fflush(stdout);
scanf("%d", &len);
for (i = len; i >= 1; i--)
list1 = add_top(list1, 100+i);
list2 = divide(list1, list_len(list1) / 2);
list_show("list1", list1);
list_show("list2", list2);
mix = merge(list2, list1);
list_show("mixed", mix);
return 0;
}
LIST divide(LIST x, int p) {
if(p&&x)
{
p--;
while(p&&x->next)
{
x=x->next;
p--;
}
LIST tmp=x->next;
x->next=NULL;
return tmp;
}
return x;
}
LIST merge(LIST x, LIST y) {
if(NULL==x)
{
return y;
}
if(NULL==y)
{
return x;
}
LIST tmp=merge(x->next,y->next);
x->next=y;
y->next=tmp;
return x;
}
length: 6
list1:101 102 103
list2:104 105 106
mixed:104 101 105 102 106 103
Process returned 0 (0x0) execution time : 1.877 s
Press any key to continue.
length: 5
list1:101 102
list2:103 104 105
mixed:103 101 104 102 105
Process returned 0 (0x0) execution time : 2.032 s
Press any key to continue.
|