题目描述
思路:新建dummy去"穿针引线"
新建一个dummy节点去"穿针引线"
注意最后返回的是dummy.next
方法一:
/**
* 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 list1, ListNode list2) {
// 创建一个dummy节点
ListNode dummy = new ListNode();
ListNode temp = dummy;
ListNode p = list1, q = list2;
while (p != null && q != null) {
if (p.val <= q.val) {
temp.next = p;
temp = p;
p = p.next;
} else if(p.val > q.val) {
temp.next = q;
temp = q;
q = q.next;
}
}
if (p == null) temp.next = q;
if (q == null) temp.next = p;
return dummy.next;
}
}
标签:dummy,ListNode,temp,val,next,链表,Hot,100,null
From: https://www.cnblogs.com/keyongkang/p/17878054.html