题目
题目链接: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 list1, ListNode list2) {
ListNode res = new ListNode();
ListNode temp = res;
ListNode index1 = list1;
ListNode index2 = list2;
while(index1!=null && index2!=null){
if (index1.val <= index2.val) {
temp.next = index1;
index1 = index1.next;
} else {
temp.next = index2;
index2 = index2.next;
}
temp = temp.next;
}
while (index1!= null) {
temp.next = index1;
temp = temp.next;
index1 = index1.next;
}
while(index2!=null){
temp.next = index2;
temp = temp.next;
index2 = index2.next;
}
return res.next;
}
}