建立长度为n1 的单链表LA和长度为n2的单链表LB,,单链表的数据和长度都由键盘输入,并编写函数将LB连接到LA,最终输出连接后的单链表的所有元素
时间: 2024-05-25 12:16:44 浏览: 105
两个线性表连接-单链表
#include <stdio.h>
#include <stdlib.h>
//定义单链表结构体
typedef struct node{
int data;
struct node *next;
}Node, *LinkedList;
//创建单链表
LinkedList createLinkedList(int n){
LinkedList head, p, q;
int i, num;
head = (LinkedList)malloc(sizeof(Node));
head->next = NULL;
q = head;
for(i=0; i<n; i++){
printf("请输入第%d个节点的值:", i+1);
scanf("%d", &num);
p = (LinkedList)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
//输出单链表
void printLinkedList(LinkedList head){
LinkedList p = head->next;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//将LB连接到LA
void connectLinkedList(LinkedList LA, LinkedList LB){
LinkedList p = LA;
while(p->next){
p = p->next;
}
p->next = LB->next;
free(LB);
}
int main(){
int n1, n2;
LinkedList LA, LB;
printf("请输入单链表LA的长度:");
scanf("%d", &n1);
LA = createLinkedList(n1);
printf("请输入单链表LB的长度:");
scanf("%d", &n2);
LB = createLinkedList(n2);
printf("连接前的单链表LA:");
printLinkedList(LA);
printf("连接前的单链表LB:");
printLinkedList(LB);
connectLinkedList(LA, LB);
printf("连接后的单链表LA:");
printLinkedList(LA);
return 0;
}
阅读全文