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

}
相关推荐
砍材农夫1 小时前
物联网 基于netty构建mqtt协议规范(主题通配符订阅)
java·前端·javascript·物联网·netty
LuminousCPP1 小时前
数据结构 - 线性表第三篇:基于顺序表实现 C 语言通讯录(基础功能篇)
c语言·数据结构·经验分享·笔记·算法
_日拱一卒1 小时前
LeetCode:114二叉树展开为链表
java·开发语言·算法
李小狼lee1 小时前
《spring如此简单》第四节--IOC思想的实现,spring启动后发生了什么
后端·面试
天天进步20151 小时前
从零打造 Python 全栈项目:智能教学辅助系统
开发语言·人工智能·python
2301_800895101 小时前
计算机网络保研面试(自用版h)
计算机网络·面试
SamDeepThinking1 小时前
面试官问Bean线程安全,你该从架构角度回答
java·后端·面试
敖正炀1 小时前
ArrayList 与 LinkedList 源码全景:从数据结构选择到性能分歧的完整代码路径
java
凌波粒1 小时前
LeetCode--513.找树左下角的值(二叉树)
java·算法·leetcode
敖正炀1 小时前
HashMap 红黑树化与退化
java