题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:

解析:
采用双指针,分别指向两个链表,然后将两个链表较小的那个添加到新链表中
1 /**
2 * Definition for singly-linked list.
3 * public class ListNode {
4 * int val;
5 * ListNode next;
6 * ListNode() {}
7 * ListNode(int val) { this.val = val; }
8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 * }
10 */
11 class Solution {
12 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
13 ListNode head = new ListNode(0);
14 ListNode tmp = new ListNode();
15 tmp = head;
16 while(list1!=null && list2!=null){
17 ListNode temp = new ListNode();
18 if(list1.val<=list2.val){
19 tmp.next=list1;
20 tmp=tmp.next;
21 list1=list1.next;
22 }
23 else{
24 tmp.next=list2;
25 tmp=tmp.next;
26 list2=list2.next;
27 }
28 tmp.next=null;
29 }
30 while(list1 == null && list2!=null){
31 tmp.next=list2;
32 tmp=tmp.next;
33 list2=list2.next;
34 tmp.next=null;
35 }
36 while(list2 == null && list1!=null){
37 tmp.next=list1;
38 tmp=tmp.next;
39 list1=list1.next;
40 tmp.next=null;
41 }
42 return head.next;
43 }
44 }
,直到两个链表都为空。
代码:
原创文章,作者:306829225,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/270266.html