数据结构第三节——链表(2)
今天(嘶,昨天忘记发了)继续链表,嘤嘤嘤…
今天尝试加入“分析”栏帮助梳理思路。
二、合并链表
先复习一下昨天那令人悲伤的例2 T_T( 不抄题了阿 )
分析
首先读入两个链表。
使用Merge函数将两个链表中的数据合并成一个链表,且保证新链表从小到大依次排列。
为此使用归并方法定义Merge()函数。
最后输出合并后的链表。
提交
#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
struct Node {
int value;
Node *next;
} a[N+10], b[N+10] ,*h1, *h2, *t1, *t2;
int n,m;
Node* Merge( Node *h1, Node *h2 ){
Node *h = NULL;
Node *t = NULL;
while( h1 || h2 ){
if ( h1 && ( h2 == NULL || ( h1 -> value < h2 -> value )) ){
//保证h1存在
if ( h == NULL ){
h = h1;
t = h1;
}else{
t -> next = h1;
t = h1;
}
h1 = h1 -> next; //每次存入后记得 h1 —> next
}else{
if ( h == NULL ){
h = h2;
t = h2;
}else{
t -> next = h2;
t = h2;
}
h2 = h2 -> next;
}
}
return h;
}
int main(){
scanf("%d %d", &n, &m);
for ( int i = 1; i <= n; i++ ){
scanf("%d", &a[i].value );
if

本文详细介绍了链表的基本操作,包括合并链表、查找中间元素、成绩倒序输出及序列翻转等实例,并深入探讨了单向与双向链表的实现方式。
最低0.47元/天 解锁文章
1021

被折叠的 条评论
为什么被折叠?



