果然我对链表还是十分的不熟悉,很多时候写着写着就卡了,过然还要多练习才行
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
leetcode21.合并两个有序链表
思路还是比较简单的,那就是创建一个新的链表,然后依次比较两个链表的数,谁更小就先放进去。有个细节可以注意一下那就是最后如果有个链表遍历完了,另一个可以直接接上去,不需要在再遍历了。
最后的答案是:
/**
* 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 dom = new ListNode(-1);
ListNode cur = dom;
if(list1 == null)
return list2;
if(list2 == null)
return list1;
while(list1 != null && list2 != null)
{
if(list1.val <= list2.val)
{
cur.next = list1;
list1 = list1.next;
}
else
{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if(list1 == null)
{
cur.next = list2;
}
else
cur.next = list1;
return dom.next;
}
}