#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* createNode(int data)//初始化链表
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(struct Node* head, int data)//将数据加入成为链表的一部分
{
struct Node* newNode = createNode(data);
struct Node* curr = head;
while (curr->next != NULL)
curr = curr->next;
curr->next = newNode;
}
void printList(struct Node* head)//输出链表
{
struct Node* curr = head->next;
while (curr != NULL)
{
printf("%d ", curr->data);
curr = curr->next;
}
printf("\n");
}
void mergeLists(struct Node* list1, struct Node* list2)//将两个非递减有序单链表合并成一个非递减有序单链表
{
//========begin=======
struct Node *mergeList = createNode(0);
struct Node *c = mergeList;
struct Node *c1 = list1->next ;
struct Node *c2 = list2->next ;
while(c1 != NULL&&c2 != NULL)
{
if(c1->data <= c2->data)
{
c->next = c1;
c1 = c1->next;
}
else
{
c->next = c2;
c2 = c2->next;
}
c = c->next;
}
if(c1 != NULL)
{
c->next = c1;
}
else
{
c->next = c2;
}
list1->next = mergeList->next ;
free(mergeList);
//=========end========
}
void freeList(struct Node* head) //释放节点所占的内存空间
{
struct Node* curr = head;
while (curr != NULL)
{
struct Node* temp = curr;
curr = curr->next;
free(temp);
}
}
int main()
{
struct Node* list1 = createNode(0);
struct Node* list2 = createNode(0);
int m, n, i, x;
scanf("%d", &m); //输入第一个链表
for (i = 0; i < m; i++)
{
scanf("%d", &x);
insertNode(list1, x);
}
//========begin=======
//和输入第一个单链表一样,输入第二个链表
scanf("%d",&n);
for(i = 0;i < n;i++)
{
scanf("%d",&x);
insertNode(list2,x);
}
//=========end========
mergeLists(list1, list2); //合并链表
printList(list1);
freeList(list1);
freeList(list2);
return 0;
}