1.已知两个链表head1和head2各自有序,请把它们合并成一个链表依然有序。(保留所有节点,即便大小相同)
typedef struct Node
{
int data;
struct Node *next;
}Node, *PNode;
Node *link(Node *head1,Node *head2)
{
if(head1 == NULL)
return head2;
if(head2 == NULL)
return head1;
Node *head = NULL;
Node *temp1 = NULL;
Node *temp2 = NULL;
if(head1->data < head2->data)//升序排列
{
head = head1;
temp1 = head1->next;
temp2 = head2;
}
else
{
head = head2;
temp1 = head1;
temp2 = head2->next;
}
Node *temp3 = head;
while(temp1 != NULL && temp2 != NULL)
{
if(temp1->data < temp2->data)
{
temp3->next = temp1;
temp3 = temp3->next;
temp1 = temp1->next;
}
else
{
temp3->next = temp2;
temp3 = temp3->next;
temp2 =temp2->next;
}
}
if(temp1 == NULL)
temp3->next = temp2;
if(temp2 == NULL)
temp3->next = temp1;
return head;
}
int main()
{
/* int a[5]={'1','0','2'};
int *p;
p = a;
printf("%d\n",sizeof(a));
*/
Node *head1 = NULL;
Node *head2 = NULL;
Node *p1 = NULL;
Node *p2 = NULL;
Node *p3 = NULL;
head1 = (Node *)malloc(sizeof(struct Node));
head2 = (Node *)malloc(sizeof(struct Node));
p1 = (Node *)malloc(sizeof(struct Node));
p2 = (Node *)malloc(sizeof(struct Node));
head1->data = 1;
p1->data =2;
p1->next = NULL;
head1->next = p1;
head2->data = 3;
p2->data = 4;
p2->next = NULL;
head2->next = p2;
p3 = link(head1, head2);
Node* p = NULL;
Node* pfree = NULL;
p = p3;
int i=0;
for(i=0;p != NULL;i++)
{
printf("%d:%d\n",i,p->data);
pfree= p;
p = p->next;
free(pfree);
}
}