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

}
相关推荐
延凡科技21 分钟前
多场景落地复盘:端边云架构无人机智能巡检系统设计与实践
大数据·数据结构·人工智能·科技·架构·无人机·能源
心平气和量大福大40 分钟前
C#-WPF-Window主窗体
开发语言·c#·wpf
莫逸风2 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
从零开始的代码生活_2 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸2 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
z123456789863 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
GIS阵地3 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
程序员Rock3 小时前
上位机开发-MODBUS面试常见问题
c语言·c++·面试·职场和发展·上位机
yaoxin5211233 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
groundhappy3 小时前
idalib安装和codex ida-mcp配置
linux·开发语言·python