将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。leetcode21,牛客

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;
	}
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值