遇见YY

导航

 

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4


class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
}
}



public class
Solution { public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); Solution solution = new Solution(); ListNode listNode = solution.mergeTwoLists(l1, l2); while (listNode!=null){ System.out.println(listNode.val); listNode = listNode.next; } } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newHead = new ListNode(-1); ListNode newHeadPoint = newHead; while (l1!=null || l2!=null){ if (l1==null){ newHeadPoint.next = l2; break; } if (l2==null) { newHeadPoint.next = l1; break; } if (l1.val < l2.val){ newHeadPoint.next = l1; newHeadPoint = newHeadPoint.next; l1 = l1.next; continue; } else { newHeadPoint.next = l2; newHeadPoint = newHeadPoint.next; l2 = l2.next; continue; } } return newHead.next; } }

 

posted on 2020-09-17 20:47  一骑红尘妃子笑!  阅读(134)  评论(0编辑  收藏  举报