题目
解题思路
题目一看是和链表相关的,而且是两个链表,那肯定核心思路和双指针相关了。
我们来一步步拆分问题:
- 首先我们要把给我们的链表构建出来,所以需要一个Node类,以及一个buildNode的方法。
- 那么输入给我们的是一个Node的三个属性,我们可以构建一个key:地址 val:Node对象的MAP,用来辅助构造
List<Node>
(为啥是构造的List<Node>
呢,是因为这题将数组作为链表,比较好处理,不然链表的next,pre,处理起来比较麻烦)。 - 经过上面两步,已经构建出来两个
List<Node>
了,此时我们进行倒序合并,这里就用核心逻辑双指针,指针1指向长链表的开头,指针2指向短链表的结尾(指针2向后移动以达到倒序插入的效果),我们有长短两个链表,需求是短的倒序后隔两个往长的插,所以我们只需要遍历长链表,存储一个count
,count % 2 == 0
代表了隔两个元素。 - res构建出来后这个时候虽然Node的顺序对了,但是node内部的值nextAddress还是老的,需要更新为新顺序的address:
res.get(i).nextAddress = res.get(i + 1).address;
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] firstData = sc.nextLine().split(" ");
String firstHeadAddress = firstData[0];
String secondHeadAddress = firstData[1];
int totalSize = Integer.parseInt(firstData[2]);
//key:地址 val:Node对象
Map<String,Node> addressNodeMap = new HashMap<>();
//构建nodeMap
for(int i =0; i < totalSize; i++){
String[] tmpList = sc.nextLine().split(" ");
String curAdd = tmpList[0];
int curVaule = Integer.parseInt(tmpList[1]);
String nextAdd = tmpList[2];
Node node = new Node(curAdd, curVaule, nextAdd);
addressNodeMap.put(curAdd, node);
}
//构建List<Node>
List<Node> firstNodeList = buildNodeList(firstHeadAddress,addressNodeMap);
List<Node> secondNodeList = buildNodeList(secondHeadAddress,addressNodeMap);
//为了确保fifirstNodeList就是长的那个,进行二次置换
if(firstNodeList.size() < secondNodeList.size()){
List<Node> tmpVal = new ArrayList<>();
tmpVal = firstNodeList;
firstNodeList = secondNodeList;
secondNodeList = tmpVal;
}
//核心逻辑:进行倒序合并
List<Node> res = new ArrayList<>();
int firstPointer = 0;
//短的指针从尾部开始扫,这样就达到了倒序的目的
int secondPointer = secondNodeList.size()-1;
int count = 0;
for (int i = 0; i < firstNodeList.size(); i++) {
res.add(firstNodeList.get(i));
count++;
// 每隔两个元素插入一个短链表元素
if (count % 2 == 0 && secondPointer >= 0) {
res.add(secondNodeList.get(secondPointer));
secondPointer--;
}
}
for (int i = 0; i < res.size() - 1; i++) {
if(i == res.size()-1){
res.get(res.size() - 1).nextAddress = "-1";
}else{
res.get(i).nextAddress = res.get(i + 1).address;
}
}
//转化成对应的格式输出
for (Node node : res) {
System.out.println(node.address + " " + node.data + " " + node.nextAddress);
}
}
//通过nodeMap来构建List<Node>
public static List<Node> buildNodeList(String headAddress, Map<String,Node> addressNodeMap){
List<Node> tmpRes = new ArrayList<>();
String curAddress = headAddress;
while(true){
if(addressNodeMap.get(curAddress) == null){
break;
}
Node tmpNode = addressNodeMap.get(curAddress);
tmpRes.add(tmpNode);
curAddress = tmpNode.nextAddress;
}
return tmpRes;
}
public static class Node{
String address;
int data;
String nextAddress;
public Node(String address, int data, String nextAddress) {
this.address = address;
this.data = data;
this.nextAddress = nextAddress;
}
}
}