因为要求不改变原链表,所以需要用申请内存来产生新的链表。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node {
int v;
struct node *next;
}Node;
Node *merge(Node *list1, Node *list2)
{
Node *list = NULL, *node = NULL, *tmp = NULL;
if(NULL == list1)
{
return list2;
}
if(NULL == list2)
{
return list1;
}
list = (Node *)malloc(sizeof(Node));
list->next = NULL;
if(list1->v < list2->v)
{
list->v = list1->v;
list1 = list1->next;
}
else
{
list->v = list2->v;
list2 = list2->next;
}
node = list;
while(list1 && list2)
{
tmp = (Node *)malloc(sizeof(Node));
memset(tmp, 0, sizeof(Node));
if(list1->v < list2->v)
{
tmp->v = list1->v;
list1 = list1->next;
}
else if(list1->v == list2->v)
{
tmp->v = list1->v;
list1 = list1->next;
list2 = list2->next;
}
else
{
tmp->v = list2->v;
list2 = list2->next;
}
node->next = tmp;
node = node->next;
}
if(NULL == list1 && NULL == list2)
{
return list;
}
else if(NULL == list1)
{
while(list2)
{
tmp = (Node *)malloc(sizeof(Node));
memset(tmp, 0, sizeof(Node));
tmp->v = list2->v;
list2 = list2->next;
node->next = tmp;
node = node->next;
}
}
else
{
while(list1)
{
tmp = (Node *)malloc(sizeof(Node));
memset(tmp, 0, sizeof(Node));
tmp->v = list1->v;
list1 = list1->next;
node->next = tmp;
node = node->next;
}
}
return list;
}
void free_list(Node *list)
{
Node *tmp = NULL;
while(list)
{
tmp = list->next;
free(list);
list = tmp;
}
}
void print_list(Node *list)
{
while(list)
{
printf("%u ", list->v);
list = list->next;
}
printf("\n");
}
int main(int argc, char *argv[])
{
Node *list1 = NULL;
Node *list2 = NULL;
Node *list = NULL;
int len, i;
printf("Please input the len of list1:");
scanf("%u", &len);
list1 = (Node *)malloc(len * sizeof(Node));
for(i=0; i<len; i++)
{
scanf("%u", &list1[i].v);
if(i == len - 1)
{
list1[i].next = NULL;
}
else
{
list1[i].next = &list1[i+1];
}
}
printf("Please input the len of list2:");
scanf("%u", &len);
list2 = (Node *)malloc(len * sizeof(Node));
for(i=0; i<len; i++)
{
scanf("%u", &list2[i].v);
if(i == len - 1)
{
list2[i].next = NULL;
}
else
{
list2[i].next = &list2[i+1];
}
}
print_list(list1);
print_list(list2);
list = merge(list1, list2);
print_list(list);
free(list1);
free(list2);
free_list(list);
return 0;
}