题目 | Merge Two Sorted Lists |
通过率 | 33.2% |
难度 | Easy |
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
关键点:定义一个新的指针,然后取出两个链表中各自的第一个元素进行比较,将较小者加入新链表。最后当其中一个链表变为空后,将另一个链表剩余所有元素加入新链表。
java代码:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode p1=l1; ListNode p2=l2; ListNode mergedList = new ListNode(0); ListNode p=mergedList; while(p1!=null&&p2!=null){ if(p1.val<=p2.val){ p.next=p1; p1=p1.next; }else{ p.next=p2; p2=p2.next; } p=p.next; } if(p1!=null){ p.next=p1; } if(p2!=null){ p.next=p2; } return mergedList.next; } }