比如:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
LinkedList mergeTwoLists(Node* head1, Node* head2)
{
if (head1 == NULL)
{
return head2;
}
if (head2 == NULL)
{
return head1;
}
Node *newList = NULL; //创建新的链表,把数据排序进去
Node *curList = NULL;
newList = curList = (Node *)malloc(sizeof(Node));
while (head1 && head2)
{
if (head1->data > head2->data)
{
curList->next = head2;
head2 = head2->next;
}
else
{
curList->next = head1;
head1 = head1->next;
}
curList = curList->next;
}
if (head1)
{
curList->next = head1;
}
else
{
curList->next = head2;
}
Node* p = newList;
newList = newList->next;
free(p); //释放申请的空间
return newList;
}
int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 3);
append(&head1, 4);
append(&head1, 6);
LinkedList head2 = NULL;
append(&head2, 1);
append(&head2, 2);
append(&head2, 5);
append(&head2, 7);
printf("Original List1: ");
printList(head1);
printf("Original List2: ");
printList(head2);
LinkedList head = mergeTwoLists(head1, head2);
printf("mergeTwoLists List: ");
printList(head);
system("pause");
return 0;
}
这个是比较详细的说明:https://mp.weixin.qq.com/s/0TiG9cF_la77aW_jUZf53w
CSDN:https://blog.csdn.net/efls111/article/details/134351938