在看链表的相关内容时,有关于两个链表合并的题目,故整理记录,以备复习:
题目要求:
对于两个有序的链表:
例如:
L1 = {8, 6,2}
L2 = {9 ,7, 5, 3, 1}
两个链表进行合并,合并后的结果为:
L = {9 , 8 , 7, 6, 5, 3, 2, 1}
L1 = NULL
L2 = NULL
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode * List;
struct LNode{
int data;
struct LNode* next;
};
List MakeList01(int length) //创建链表1 带头结点的头插法
{
List p;
if(length<1)
{
return NULL;
}
List head = (List)malloc(sizeof(struct LNode));
head->next = NULL;
int j = 1;
while(j<=length)
{
p = (List)malloc(sizeof(struct LNode));
p->data = j+2;
p->next = head->next;
head->next = p;
j++;
}
return head;
}
List MakeList02(int length) //创建链表2 带头结点的头插法
{
List p;
if(length<1)
{
return NULL;
}
List head = (List)malloc(sizeof(struct LNode));
head->next = NULL;
int j = 1;
while(j<=length)
{
p = (List)malloc(sizeof(struct LNode));
p->data = j+1;
p->next = head->next;
head->next = p;
j++;
}
return head;
}
List Merge(List L1,List L2)
{
List L = (List)malloc(sizeof(struct LNode));
List head = L;
List p1 = L1->next;
List p2 = L2->next;
while(p1 && p2)
{
if(p1->data>=p2->data)
{
L->next = p1;
p1 = p1-> next;
}
else
{
L->next = p2;
p2 = p2->next;
}
L = L->next;
}
if(p1)
{
L->next = p1;
}
if(p2)
{
L->next = p2;
}
L1->next = NULL;
L2->next = NULL;
return head;
}
List merge(List L1,List L2)
{
List head = (List)malloc(sizeof(struct LNode));
List p1 = L1->next;
List p2 = L2->next;
List p3 = head;
while(p1&&p2) {
if (p1->data >= p2->data) {
p3->next = p1;
p1 = p1->next;
}
else
{
p3->next = p2;
p2 = p2->next;
}
p3 = p3->next;
}
if(p1)
p3->next = p1;
if(p2)
p3->next = p2;
L1->next = NULL;
L2->next = NULL;
return head;
}
void PrintList(List L)
{
List p = L->next; //注意,如果打印原始的列表,需要这个语句
//List p = L; //注意,如果打印从某一位置的链表,用这个
if(!p)
{
return;
}
while(p)
{
printf("%d ",p->data);
p = p->next;
}
}
int main()
{
List L,L1,L2;
L1 = MakeList01(3);
PrintList(L1);
printf("\n");
L2 = MakeList02(3);
PrintList(L2);
printf("\n");
L = Merge(L1,L2);
PrintList(L);
printf("\n");
return 0;
}