已知有两个链表a和b,结点类型相同,均包括一个int类型的数据。编程把两个链表合并成一个,结点按升序排列 |
---|
题目
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct DATA)
struct DATA
{
long num;
struct DATA *next;
};
struct DATA *create(int n)
{
struct DATA *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct DATA *)malloc(LEN);
scanf("%ld",&p1->num);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
struct DATA *merge(struct DATA *head, struct DATA *head2)
{
_______________________
return head;
}
struct DATA *insert(struct DATA *head, struct DATA *d)
{
_______________________
return head;
}
struct DATA *sort(struct DATA *head)
{
_______________________
return head;
}
void print(struct DATA *head)
{
struct DATA *p;
p=head;
while(p!=NULL)
{
printf("%ld",p->num);
p=p->next;
printf("\n");
}
}
main()
{
struct DATA *head, *head2;
int n;
long del_num;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
head2=create(n);
head = merge(head, head2);
head = sort(head);
print(head);
}
答案
#include "stdio.h"
#include "malloc.h"
#define LEN sizeof(struct DATA)
struct DATA
{
long num;
struct DATA *next;
};
struct DATA *create(int n)
{
struct DATA *head=NULL,*p1=NULL,*p2=NULL;
int i;
for(i=1;i<=n;i++)
{ p1=(struct DATA *)malloc(LEN);
scanf("%ld",&p1->num);
p1->next=NULL;
if(i==1) head=p1;
else p2->next=p1;
p2=p1;
}
return(head);
}
struct DATA *merge(struct DATA *head, struct DATA *head2)
{
struct DATA *p; //创建一个指针
p = head; //因为最后return的是头结点,所以用p来等同头结点,保持头结点的地址不变
while (p->next != NULL) //循环找到尾节点 若这里p是head的话是错误的
{
p = p->next;
}
//循环结束后p代表的是尾节点
p->next = head2; //尾节点连接head2
return head;
}
struct DATA *insert(struct DATA *head, struct DATA *d)
{
struct DATA *p;
p = head; //因为最后return的是头结点,所以用p来等同头结点,保持头结点的地址不变
if (p ==NULL) //若头结点为空,则返回插入的节点
{
return d;
}
while (p->next->num < d->num&&p != NULL) //循环找到新节点的插入位置
{
p = p->next;
}
d->next = p->next; //用d->next存下p->next的地址
p->next = d; //这时候p->next就可以指向d了,并且d->next指向的是原来的p的next
return head;
}
struct DATA *sort(struct DATA *head)
{
//使用冒泡排序
struct DATA *i, *j, *p, p1;
p = head; //因为最后return的是头结点,所以用p来等同头结点,保持头结点的地址不变
for (i = head; i->next != NULL; i = i->next) //注意for里的三个语句都是跟指针有关的
{
for (j = head; j->next != NULL; j = j->next) //注意for里的三个语句都是跟指针有关的
{
if (j->num > j->next->num) //发现两个节点顺序不对时,不需要交换整个节点,交换节点数据域就好
{
long t = j->num; //定义相同类型的t来保存num
j->num = j->next->num;
j->next->num = t;
}
}
}
return head;
}
void print(struct DATA *head)
{
struct DATA *p;
p=head;
while(p!=NULL)
{
printf("%ld",p->num);
p=p->next;
printf("\n");
}
}
main()
{
struct DATA *head, *head2;
int n;
long del_num;
scanf("%d",&n);
head=create(n);
scanf("%d",&n);
head2=create(n);
head = merge(head, head2);
head = sort(head);
print(head);
}