两个顺序单链表合并
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node ;
Node *create_list(int *array,const int length)
{
if(array==NULL||length<=0)
{
return NULL;
}
Node *head = (Node*)malloc(sizeof(Node));
head->data = array[0];
Node *p,*q = head;
for(int i=1;i<length;i++)
{
p = (Node*)malloc(sizeof(Node));
p->data = array[i];
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
Node *merger(Node *alist,Node *blist)
{
if(alist==NULL)
{
return blist;
}
if(blist==NULL)
{
return alist;
}
Node *p = alist;
Node *q = blist;
Node *head,*pos;
if(p->data < q->data)
{
head = p; //值小的结点为首结点
p = p->next;
} else {
head = q;
q = q->next;
}
pos = head;
while(p!=NULL&&q!=NULL)//两个链表都不为空时,才可进行比较
{
if(p->data < q->data)
{
pos->next = p;
pos = p;
p = p->next;
} else {
pos->next = q;
pos = q;
q = q->next;
}
}
if(p==NULL)
{
pos->next = q;
}
if(q==NULL)
{
pos->next = p;
}
return head;
}
void print(Node *head)
{
Node *p = head;
while(p!=NULL)
{
fprintf(stdout,"%d ",p->data);
p = p->next;
}
}
int main(void)
{
int a[] = {1,2,3,4,6,90};
int b[] = {0,3,5,6,7,60};
const int lenofa = sizeof(a)/sizeof(int);
const int lenofb = sizeof(b)/sizeof(int);
Node *alist = create_list(a,lenofa);
Node *blist = create_list(b,lenofb);
print(alist);
printf("\n");
print(blist);
printf("\n");
Node * head = merger(alist,blist);
print(head);
printf("\n");
return 0;
}