更多试卷真题,点击:华为OD2023真题试卷列表,刷题必点
寻找链表的中间结点
知识点链表数组
时间限制:1s 空间限制:256MB 限定语言:不限
题目描述:
给定一个单链表 L,请编写程序输出 L 中间结点保存的数据。如果有两个中间结点,则输出第二个中间结点保存的数据。
例如:给定 L 为 1→7→5,则输出应该为 7;给定 L 为 1→2→3→4,则输出应该为 3。
输入描述:
每个输入包含 1 个测试用例。每个测试用例第 1 行给出链表首结点的地址、结点总个数正整数 N (≤105)。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。
接下来有 N 行,每行格式为:
Address Data Next
其中 Address 是结点地址,Data 是该结点保存的整数数据(0 ≤ Data ≤ 108),Next 是下一结点的地址。输出描述:
对每个测试用例,在一行中输出 L 中间结点保存的数据。如果有两个中间结点,则输出第二个中间结点保存的数据。
补充说明:
已确保输入的结点所构成的链表 L 不会成环,但会存在部分输入结点不属于链表 L 情况 。
示例1
输入:
00100 4
00000 4 -1
00100 1 12309
33218 3 00000
12309 2 33218
输出:
3
示例2
输入:
10000 3
76892 7 12309
12309 5 -1
10000 1 76892
输出:
7
JAVA代码满分
import java.util.*;
// 注意类名必须为 Main
public class Main {
public static class Node{
String data;
String next;
public Node(String data,String next){
this.data = data;
this.next = next;
}
}
public static void main(String[] args) {
// 通过map快速寻址
Map<String,Node> map = new HashMap<>();
Scanner in = new Scanner(System.in);
// 初始化元信息和具体数据
String[] mate = in.nextLine().split(" ");
for(int i = 0 ; i < Integer.parseInt(mate[1]); i ++){
String[] info = in.nextLine().split(" ");
map.put(info[0],new Node(info[1],info[2]));
}
// 因为存在为空的数据,通过list保存有效数据和记录数据链长度
List<String> res = new LinkedList<>();
String address = mate[0];
while(true){
if(!map.containsKey(address)){
break;
}
// 记录当前节点,并指向下一个节点
Node node = map.get(address);
res.add(node.data);
address = node.next;
}
// 返回中间第二个(如果有)的值
int idx = (res.size()) / 2;
System.out.println(res.get(idx));
}
}
JavaScript代码满分
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
// Write your code here
let [first, count] = (wait readline()).split(' ');
count = Number(count);
const nodeMap = {};
// 接收链表数据
while(line = await readline()){
let node = line.split(' ');
const [addr, value, next] = node
nodeMap[addr] = { value, next }
}
// 可能有节点不属于链表, 求链表真实长度
let lineLength = 1
let current = nodeMap[first]
while(current.next !== '-1') {
current = nodeMap[current.next]
lineLength++
}
let center = Math.floor(lineLength / 2)
let currNode = nodeMap[first]
while(center--) {
currNode = nodeMap[currNode.next]
}
// 输出结果
console.log(currNode.value)
}()