题目:力扣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 ans = new ListNode(0);
ListNode cur = ans;
while(l1!=null && l2!=null){
if(l1.val < l2.val){
cur.next = l1;
cur = cur.next;
l1 = l1.next;
}else{
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
if(l1==null){
cur.next = l2;
}else{
cur.next = l1;
}
return ans.next;
}
}
思路:新建一个链表ans,对比l1和l2结点大小,较小者先放入新链表中,然后原链(l1或l2)表所指的结点位置向后移,直至原链表有一条链去到尽头位置,将另一条链直接接在其尾部。最后返回ans.next即可。
1.新建一个链表ans,用于存储l1和l2合并后的链表。cur指向所需要操作结点的位置。
ListNode ans = new ListNode(0);
ListNode cur = ans;
2.让l1的结点与l2的结点一一对比,较小者先添入到ans链表,然后原链表向后移动,直至有有一条原链表移动至最后位置。
while(l1!=null && l2!=null){
if(l1.val < l2.val){
cur.next = l1;
cur = cur.next;
l1 = l1.next;
}else{
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
3.判断是哪一条链到了最后位置,然后将另一条链直接接在其后面即可。
if(l1==null){
cur.next = l2;
}else{
cur.next = l1;
}
4.将完成上述操作的链表头结点返回。
return ans.next;