代码:
#include
#include
//这里要利用A B原有空间 所以就可以损坏A B两个链表 且不能创建新的结点了
//这是这一题跟上一题最大的不同
typedef struct node
{
int data;
struct node * next;
}Node;
typedef struct list
{
Node* head;
Node* tail;
}List;
void Init_list(List* L)
{
Node* first = (Node*)malloc(sizeof(Node));
if(!first)
printf("wrong!\n");
first -> data = 0;
first -> next = NULL;
L->head = L->tail = first;
int length;
printf("please enter list length: ");
scanf("%d",&length); //scanf里面不能写类似于printf中打印字符串的语句
for(int i = 0; i< length; i++)
{
Node* new = (Node*)malloc(sizeof(Node));
scanf("%d",&new -> data); //这个语句注意一下
new -> next = NULL;
L->tail -> next = new;
L->tail = new;
}
}
void merge(List* l1,List l2)
{
Node *p, *q,*save,*prev;
p = l1->head; q = l2.head;
//用l1来存储新的链表
while(p && q)
{
if(p->data < q->data)
{
prev = p;
p = p->next;
}
else if(p->data > q->data)
{
save = q;
q = q->next;
prev->next = save;
save->next = p;
}
else
{
prev = p;
p = p -> next;
q = q-> next;
}
}
//将最后一个元素归到链表中
if(q == NULL)
;
else
{
p -> next = q;
}
}
void print_list(List L)
{
Node* p;
p = L.head->next;
while(p != NULL)
{
printf("%d ",p->data);
p = p -> next;
}
printf("\n");
}
int main(int argc, char const *argv[])
{
List l1,l2;
Init_list(&l1);
Init_list(&l2);
merge(&l1,l2);
printf("--------------------\n");
printf("after merge: ");
print_list(l1);
//printf("l2: ");
//print_list(l2);
return 0;
}
运行截图: