函数题:单链表的显示
需要写出输出该线性表的所有元素的子函数
该程序实现将两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
### 函数接口定义:
c++
void showList(List *head)
head是用户参数,代表需要遍历的单链表的头元素地址
### 裁判测试程序样例:
c
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
int data;
struct node *next;
} List;
List *CreateList() //创建链表,注意带头结点和不带头结点的区别
{
int num;
List *head,*cnew,*tail;
head = (List*)malloc(sizeof(List));
head->next = NULL;
while(1)
{
scanf("%d",&num);
if(num==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;
}
void showList(List *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);
}
/* 请在这里填写答案 */
### 输入样例:
in
1 3 5 7 9 0
2 4 6 8 10 0
### 输出样例:
out
10 9 8 7 6 5 4 3 2 1
答案:若无答案欢迎评论
该程序实现将两个单链表归并为一个按元素值递减次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
### 函数接口定义:
c++
void showList(List *head)
head是用户参数,代表需要遍历的单链表的头元素地址
### 裁判测试程序样例:
c
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
int data;
struct node *next;
} List;
List *CreateList() //创建链表,注意带头结点和不带头结点的区别
{
int num;
List *head,*cnew,*tail;
head = (List*)malloc(sizeof(List));
head->next = NULL;
while(1)
{
scanf("%d",&num);
if(num==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;
}
void showList(List *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);
}
/* 请在这里填写答案 */
### 输入样例:
in
1 3 5 7 9 0
2 4 6 8 10 0
### 输出样例:
out
10 9 8 7 6 5 4 3 2 1
答案:若无答案欢迎评论