首先要知道链表这种数据结构.
链表是有子单元结点自称.
而每个子结点由两部分组成 当前结点的值 和 指向下一个结点的 next 指针
将两个有序链表合并为一个新的有序链表并返回. 新链表是通过拼接给定的两个链表的所有节点组成的.
示例:
输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4
链接: https://leetcode-cn.com/problems/merge-two-sorted-lists
- public class ListNode {
- int val;
- ListNode next;
- public ListNode(int val) {
- this.val = val;
- }
- }
- class Solution {
- public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
- ListNode currentListNode = new ListNode(0);
- while (l1 != null && l2 != null) {
- if(l2.val> l1.val){
- currentListNode.next = l1;
- currentListNode = currentListNode.next;
- l1 = l1.next;
- } else {
- currentListNode.next = l2;
- currentListNode = currentListNode.next;
- l2 = l2.next;
- }
- }
- if (l1 == null) {
- currentListNode.next = l2;
- } else {
- currentListNode.next = l1;
- }
- return guardListNode.next;
- }
- }
来源: http://www.bubuko.com/infodetail-3325881.html