怎么构建线性表LA,LB,LC,将LA,LB合并为LC并通过主函数调用输出线性表LC,求大神帮帮忙呀!!!!!!!!

2025-03-21 23:20:48
推荐回答(1个)
回答1:

#include

#include

#include

struct node
{
int data;
struct node *next;
};

struct node * merge(struct node *head1, struct node *head2);

void destroy(struct node* head);

struct node* creatlink();

void traverse(struct node* head);

int main()
{ int c;
struct node *LC,*LA,*LB;
LA=creatlink(); //用尾插法创建链表head1,注意head1可能是空链表
LB=creatlink(); //用尾插法创建链表head2,注意head2也可能是空链表
LC=merge(LA,LB);
traverse(LC);
destroy(LC);
}
struct node * merge(struct node *head1, struct node *head2)
{

struct node *p = head1;
if(head1 == NULL)
return head2;
else
{
while(p->next != NULL)
p = p->next;

p->next = head2;
return head1;
}

}

struct node* creatlink()
{ struct node* head=NULL;
int c;
struct node *p,*q;

while(1)
{ scanf("%d",&c);
if(c==-1) break;

//申请结点空间
p = (struct node *) malloc (sizeof(struct node));

//初始化结点数据域
p->next = NULL;
p->data = c;
if(head == NULL)
{
head = p;
q=p; //设置尾指针
}
else
{
q->next = p; //挂入链尾
q=p; //设置尾指针
}
}
return head;
}

void traverse(struct node* head)
{ struct node *p=head;
while( p!=NULL) //如果p指向的结点不是空结点
{
printf("%d ",p->data); //则输出所指向的结点的数据域
p=p->next; //让p指向下一个结点
}
}

//销毁链表函数设计

void destroy(struct node* head)
{ struct node *p;
while(head!=NULL)
{
p = head;
head = head ->next;
free(p);
}
}