写一段c语言代码,首先务必注意所有函数的声明必须在main之前,否则会出现错误,另外不要使用stl。最后,代码的规范性,包括变量命名、排版、注释等也纳入考量范围。以下是这段代码的要求:Description: 假设两个按元素值非递减有序排列的线性表A和B,均以单链表作为存储结构,试编写程序,将A表和B表归并成一个按元素值非递增有序排列的线性表C,并要求利用原表(即A表和B表的)结点空间存放表C。 lnput: 第一行输入两个正整数m,n(m,n<=100),用空格分开,分别表示线性表A和B中元素个数,其后两行分别输入单链表A和B. Output: 输出单链表C。 Sample lnput: 5 5 1 3 7 12 16 2 6 7 13 20 Sample Output: 20 16 13 12 7 7 6 3 2 1
时间: 2023-05-29 09:04:14 浏览: 221
InsertAudios,c语言标准程序库stl源码剖析,c语言程序
#include<stdio.h>
#include<stdlib.h>
//定义链表节点结构体
typedef struct Node{
int data;
struct Node* next;
}Node;
//函数声明
Node* merge(Node* headA, Node* headB);
void printList(Node* head);
int main(){
//输入线性表A和B的元素个数
int m, n;
scanf("%d%d", &m, &n);
//创建链表A和B
Node* headA = NULL;
Node* headB = NULL;
Node* pA = NULL;
Node* pB = NULL;
for(int i=0; i<m; i++){
int data;
scanf("%d", &data);
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if(headA == NULL){
headA = node;
pA = node;
}
else{
pA->next = node;
pA = node;
}
}
for(int i=0; i<n; i++){
int data;
scanf("%d", &data);
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if(headB == NULL){
headB = node;
pB = node;
}
else{
pB->next = node;
pB = node;
}
}
//合并链表A和B
Node* headC = merge(headA, headB);
//输出链表C
printList(headC);
return 0;
}
//合并链表函数
Node* merge(Node* headA, Node* headB){
if(headA == NULL){
return headB;
}
if(headB == NULL){
return headA;
}
//定义链表C的头节点
Node* headC = NULL;
if(headA->data >= headB->data){
headC = headA;
headA = headA->next;
}
else{
headC = headB;
headB = headB->next;
}
//指向链表C的当前节点
Node* pC = headC;
while(headA && headB){
if(headA->data >= headB->data){
pC->next = headA;
headA = headA->next;
}
else{
pC->next = headB;
headB = headB->next;
}
pC = pC->next;
}
if(headA){
pC->next = headA;
}
else{
pC->next = headB;
}
//反转链表C
Node* pre = NULL;
Node* cur = headC;
Node* next = NULL;
while(cur){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
headC = pre;
return headC;
}
//输出链表函数
void printList(Node* head){
while(head){
printf("%d ", head->data);
head = head->next;
}
}
阅读全文