leetcode21-Merge Two Sorted Lists

题目

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

示例 1:

输入:l1 = [1,2,4], l2 = [1,3,4]

输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []

输出:[]

示例 3:

输入:l1 = [], l2 = [0]

输出:[0]

分析

用一个指针去串联俩个链表,用一个指针记录新链表的头结点

java 复制代码
public class LinkNode {
	int val;
	LinkNode next;

	public LinkNode(int data) {
		this.val = data;
		this.next = null;
	}
}
public class LinkList {
	LinkNode head;
	public LinkList() {
		this.head = null;
	}
	public LinkNode getHead() {
		return this.head;
	}
	//添加元素
	public void addNode(int data) {
		LinkNode node = new LinkNode(data);
		if (this.head == null) {
			this.head = node;
		} else {
			LinkNode cur = this.head;
			while(cur.next != null) {
				cur = cur.next;
			}
			cur.next = node;
		}
	}
	//正序打印
	public void print(LinkNode node) {
		while(node != null) {
			System.out.print(node.val);
			System.out.print(" ");
			node = node.next;
		}
		System.out.println();
	}
	public LinkNode merget(LinkNode nodea,LinkNode nodeb) {
		LinkNode head = new LinkNode(0);
		LinkNode pNode = new LinkNode(0);
		while(nodea != null && nodeb != null) {
			if(nodea.val < nodeb.val) {
				if(head.next==null) {
					head.next = nodea;
				}
				pNode.next = nodea;
				nodea = nodea.next;
				pNode = pNode.next;
			} else {
				if(head.next==null) {
					head.next = nodeb;
				}
				pNode.next = nodeb;
				nodeb = nodeb.next;
				pNode = pNode.next;

			}
		}
		while(nodea != null) {
			if(head.next==null) {
				head.next = nodea;
			}
			pNode.next = nodea;
			nodea = nodea.next;
			pNode = pNode.next;
		}
		while(nodeb != null) {
			if(head.next==null) {
				head.next = nodeb;
			}
			pNode.next = nodeb;
			nodeb = nodeb.next;
			pNode = pNode.next;
		}
		print(head.next);
		return head.next;
	}

}
public class mergeTwoSortedLists {
	public static void main(String[] args) {
		LinkList list1 = new LinkList();
		list1.addNode(1);
		list1.addNode(2);
		list1.addNode(3);
		LinkList list2 = new LinkList();
		list2.addNode(1);
		list2.addNode(3);
		list2.addNode(4);
		list1.merget(list1.getHead(),list2.getHead());
	}

}
相关推荐
chxii24 分钟前
5java集合框架
java·开发语言
老衲有点帅33 分钟前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈41 分钟前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
IsPrisoner1 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
Python私教1 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust
chicpopoo1 小时前
Python打卡DAY25
开发语言·python
yychen_java1 小时前
R-tree详解
java·算法·r-tree
JANYI20182 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式
MarkHard1232 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
王RuaRua2 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表