算法笔记练习 题解合集
题目
题目描述
知L1、L2分别为两循环单链表的头结点指针,m,n分别为L1、L2表中数据结点个数。要求设计一算法,用最快速度将两表合并成一个带头结点的循环单链表。
输入
m=5
3 6 1 3 5
n=4.
7 10 8 4
输出
3 6 1 3 5 7 10 8 4
样例输入
7
3 5 1 3 4 6 0
5
5 4 8 9 5
样例输出
3 5 1 3 4 6 0 5 4 8 9 5
思路
先生成两个循环单链表,再将其合并输出。
代码
#include <stdio.h>
#include <stdlib.h>
typedef struct lnode{
int data;
struct lnode *next;
} Lnode;
void initLinklist(Lnode *head, int n) {
int input;
Lnode *tail = head;
while (n--) {
scanf("%d", &input);
Lnode *p = (Lnode*)malloc(sizeof(Lnode));
p->data = input;
tail->next = p;
p->next = NULL;
tail = p;
}
tail->next = head;
}
void showLinklist(Lnode *head) {
Lnode *p = head->next;
while (p != head) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
int m, n;
Lnode *headA = (Lnode*)malloc(sizeof(Lnode));
Lnode *headB = (Lnode*)malloc(sizeof(Lnode));
scanf("%d", &m);
initLinklist(headA, m);
scanf("%d", &n);
initLinklist(headB, n);
// 目前为止初始化了两个循环单链表,假装题目从这里开始做
// 并且现在已知的只有两个头结点 headA,headB
Lnode *tail = headA;
if (tail->next == headA)
showLinklist(headB);
else {
while (tail->next != headA)
tail = tail->next;
tail->next = headB->next;
while (tail->next != headB)
tail = tail->next;
tail->next = headA;
free(headB);
showLinklist(headA);
}
return 0;
}