import java.util.Arrays;
import java.util.Scanner;
//链表结构,其中val代表保存的值,LinkedNode代表下一个节点的一个地址(一个变量或者说一个对象本质上就是一个地址)
class LinkedNode{
int val;
LinkedNode next;
public LinkedNode(int val,LinkedNode next) {
this.val = val;
this.next = next;
}
}
public class LinkedConcat {
public static void main(String[] args) {
//输入一个"{1,5,8},{2,6,4}"这样的实例,使用分割函数分割保存入字符串数组,再通过取出多余字符分割保存为字符串数组使用包装类中所提供的方法转化成int数组
Scanner input = new Scanner(System.in);
String[] strs = input.nextLine().split("\\}\\,\\{");
int[][] data = new int[strs.length][];
for(int i = 0;i < strs.length;i++) {
strs[i] = strs[i].replace('{', ' ').replace('}', ' ').trim();
}
for(int i = 0; i < strs.length;i++) {
String[] chars = strs[i].split(",");
data[i] = new int[chars.length];
for(int j = 0;j < chars.length;j++) {
data[i][j] = Integer.parseInt(chars[j]);
}
}
LinkedNode result = concat(createLinked(data[0]),createLinked(data[1]));
while(result != null) {
System.out.println(result.val);
result = result.next;
}
}
/**
* 基本思想就是边读取数组边创建节点然后将节点插入链表的尾部,值得注意的是头指针
* 将指定的数组转化为链表返回头指针
* @return 链表的头指针
* @param array表示需要转化为链表的数组
* */
public static LinkedNode createLinked(int[] array) {
LinkedNode head = null;
LinkedNode next = null;
for(int i = 0;i < array.length;i++) {
LinkedNode node = new LinkedNode(array[i],null);
if(i == 0) {
head = node;
next = head;
}else {
next.next = node;
next = node;
}
}
return head;
}
/**
* 思想:主要思想和两个有序数组拼接成一个数组一致,只是多了一些链表操作,先是逐个比较两个链表
* 将其中小的接入链表,等到一个链表全空了就将另外一个接入尾部
* 用于将两个链表结合并返回结合后的头指针
* @return 返回连接后的链表的头指针
* @param n1表示第一个链表的头指针
* @param n2表示第二个链表的头指针
* */
public static LinkedNode concat(LinkedNode n1,LinkedNode n2) {
if(n1 == null) {
return n2;
}
if(n2 == null) {
return n1;
}
LinkedNode head = null;
LinkedNode next = null;
while(n1 != null && n2 != null) {
if(n1.val < n2.val) {
if(head == null) {
head = n1;
n1 = n1.next;
next = head;
}else{
next.next = n1;
n1 = n1.next;
next = next.next;
}
} else {
if(head == null) {
head = n2;
n2 = n2.next;
next = head;
}else{
next.next = n2;
n2 = n2.next;
next = next.next;
}
}
}
if(n1 == null) {
next.next = n2;
}else {
next.next = n1;
}
return head;
}
}
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。leetcode21,牛客
最新推荐文章于 2024-04-26 17:02:36 发布