21. 合并两个有序链表
原题链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode re = new ListNode(); ListNode pvo = re; ListNode first = l1; ListNode second = l2; while (first != null && second != null){ if (first.val < second.val){ ListNode temp = new ListNode(first.val); first = first.next; pvo.next = temp; }else{ ListNode temp = new ListNode(second.val); second = second.next; pvo.next = temp; } pvo = pvo.next; } if (first != null){ pvo.next = first; } if (second != null){ pvo.next = second; } return re.next; } }