直接合并即可
这道题是简单题,直接合并即可
/**
- 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) {
// head是空的,返回的是head.next
ListNode head = new ListNode();
ListNode p1 = list1;
ListNode p2 = list2;
ListNode newList = head;
while (p1 != null && p2 != null) {
int value = 0;
if (p1.val <= p2.val) {
value = p1.val;
p1 = p1.next;
} else {
value = p2.val;
p2 = p2.next;
}
ListNode Node = new ListNode(value);
newList.next = Node;
newList = newList.next;
}
while (p1 != null) {
ListNode Node = new ListNode(p1.val);
p1 = p1.next;
newList.next = Node;
newList = newList.next;
}
while (p2 != null) {
ListNode Node = new ListNode(p2.val);
p2 = p2.next;
newList.next = Node;
newList = newList.next;
}
return head.next;
}
}