这个程序没有报错,就是不输出,运行完还一卡一卡的
#include
#include
int main()
{
struct node
{
int data;
struct node *next;
};
struct node *p,*q,*s,*head,*d,*o;
p=(struct node *)malloc(sizeof(struct node));
q=(struct node *)malloc(sizeof(struct node));
s =(struct node *)malloc(sizeof(struct node));
int x,y;
head=p;
while(x!=-1)
{
scanf("%d",&x);
p->data=x;
p=p->next;
}
d=q;
while(y!=-1)
{
scanf("%d",&y);
q->data=y;
q=q->next;}
o=s;
while(head->next!=NULL&&d->next!=NULL)
{
if(head->data data)
{
s->data=head->data;
head=head->next;
s=s->next;
}
else if(head->data>d->data)
{
s->data=d->data;
d=d->next;
s=s->next;
}
}
if(d->data!=NULL)
{s=d;
}
if(head->data!=NULL)
{
s=head;
}
while(o)
{
printf("%d",o->data);
if(o->next)
printf(" ");
}
}
修改如下,供参考:
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node* next;
};
struct node* create()
{
int x;
struct node* head = NULL, * p = NULL;
while (1)
{
scanf("%d", &x);
if (x == -1) break;
if (head == NULL) {
head = p = (struct node*)malloc(sizeof(struct node));
head->data = x;
head->next = NULL;
}
else {
p->next = (struct node*)malloc(sizeof(struct node));
p->next->next = NULL;
p->next->data = x;
p = p->next;
}
}
return head;
}
struct node* combin(struct node** L1, struct node** L2)
{
struct node* p1 = (*L1), * p2 = (*L2), * tail = NULL, * head = NULL, * p;
if ((*L1) == NULL && (*L2) == NULL) { //如果 L1 L2 都为空链表
return NULL;
}
if ((*L1) && (*L2)) { // 如果L1 L2 都不是空链表
while (p1 && p2) {
if (p1->data > p2->data) {
p = p2;
p2 = p2->next;
}
else {
p = p1;
p1 = p1->next;
}
if (head == NULL)
head = p;
else
tail->next = p;
tail = p;
}
tail->next = p1 ? p1 : p2;
}
else { // L1 L2 其中一个为空链表
head = (*L1) ? (*L1) : (*L2);
}
(*L1) = NULL; (*L2) = NULL;
return head;
}
void print(struct node* head)
{
struct node* p = head;
if (!head) {
printf("NULL\n");
}
else{
while (p) {
printf(p == head ? "%d" : " %d", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
struct node* head1 = NULL, * head2 = NULL, * head3 = NULL;
head1 = create();
head2 = create();
head3 = combin(&head1, &head2);
print(head3);
return 0;
}
最后的while循环中,你的o指向没改变啊,不就死循环了。
o=o->next
输入的时候 p=p->next;,这个p->next;可是NULL,这里需要分配内存保存输入的数据。
整个程序就分配了3个头结点的内存,其他节点都没有分配内存。