将两个递增的有序列表合并为一个递增的有序列表
#include "pch.h"
#include <iostream>
#include<string>
#define Maxsize 1000
using namespace std;
struct list
{
int data;
list *next;
};
list* link(list *l1, list *l2)
{
list *p1, *p2,*head,*p;
p1 = l1->next;
p2 = l2->next;
head = new list;
head->next = NULL;
p = head;
if (p1 == NULL) return l2;
if (p2 == NULL) return l1;
while (p1!=NULL&&p2!=NULL)
{
if (p1->data < p2->data) {
p->next = p1;
p1 = p1->next;
}
else {
p->next = p2;
p2 = p2->next;
}
p = p->next;
}
if (p1 == NULL) p->next = p2;
else p->next = p1;
return head->next;
}
void insert(list *&head, int i)
{
list *in=new list;
in->data = i;
in->next = NULL;
list*p;
p = head;
while (p->next!=NULL)
{
p = p->next;
}
p->next = in;
}
int main()
{
int i = 0;
list *l1 = new list;
list *l2 = new list;
l1->next = NULL;
l2->next = NULL;
while (i<5)
{
insert(l1, i * 2 + 1);
insert(l2, i * 2);
i++;
}
list *head;
head=link(l1, l2);
list *p = head;
while (p != NULL)
{
cout << p->data << '\t';
p = p->next;
}
}