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

}
相关推荐
Flittly1 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
Ruihong2 小时前
Vue withDefaults 转 React:VuReact 怎么处理?
vue.js·react.js·面试
小兔崽子去哪了2 小时前
Java 生成二维码解决方案
java·后端
kyriewen2 小时前
别再这样写 async/await 了:我在 Code Review 中见过最多的 8 个错误
前端·javascript·面试
人活一口气6 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
烬羽8 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
云技纵横8 小时前
一个 @Async,把 @Transactional 的事务边界打穿了
后端·面试
想要成为糕糕手8 小时前
Harness Engineering:大模型时代的“马鞍”——从记忆层开始,让AI真正为你所用
面试·ai编程·claude
NE_STOP8 小时前
Vibe Coding -- 完整项目案例实操
java
荣码8 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python