本题要求写出输出单链表所有元素的子函数。
该程序实现将两个单链表归并为一个按元素值递减次序排列的单链表,并利用原来两个单链表的结点存放归并后的单链表。
【本题只是要求打印输出单链表所有元素】,并非求单链表的合并。
个人参考答案:
void showList(List *head)
{
List *cur = head->next; // 从头结点之后的第一个节点开始
while (cur)
{
printf("%d ",cur->data);// 打印当前节点的数据
cur = cur->next; // 移动到下一个节点
}
}
函数接口定义:
void showList(List *head);
head是用户参数,代表需要遍历的单链表的头元素地址
裁判测试程序样例:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
int data;
struct node *next;
} List;
/* 【 本题要求函数 】 */
void showList(List *head);
List *CreateList() //创建链表,注意带头结点和不带头结点的区别
{
int num;
List *head,*cnew,*tail;
head = (List*)malloc(sizeof(List));
head->next = NULL;
tail = head;
while(1)
{
scanf("%d",&num); // 某些编译器要求此处改为scanf_s
if(num==0) // 输入为0时结束建表
break;
cnew = (List*)malloc(sizeof(List));
cnew->data = num;
cnew->next = NULL;
if(head->next==NULL)
head->next = cnew;
else
tail->next = cnew;
tail = cnew;
}
return head;
}
List *List_merge(List *La,List *Lb)
{
List *p,*q,*r;
p = La->next;
La->next = NULL;
q = Lb->next;
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data) //尾插法,结果与插入顺序相反
{
r = p->next;
p->next = La->next;
La->next = p;
p = r;
}
else
{
r = q->next;
q->next = La->next;
La->next = q;
q = r;
}
}
while(p!=NULL)
{
r = p->next;
p->next = La->next;
La->next = p;
p = r;
}
while(q!= NULL)
{
r = q->next;
q->next = La->next;
La->next = q;
q = r;
}
return La;
}
int main()
{
List *head1,*head2;
head1 = CreateList();
head2 = CreateList();
head1 = List_merge(head1,head2);
showList(head1);
}
/* 请在这里填写答案 */
输入样例:
1 3 5 7 9 0
2 4 6 8 10 0
输出样例:
10 9 8 7 6 5 4 3 2 1