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.
/**
* 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 dummy= new ListNode(0);
ListNode runner= dummy;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
runner.next=l1;
l1=l1.next;
}else{
runner.next=l2;
l2=l2.next;
}
runner=runner.next;
}
if(l1!=null){
runner.next=l1;
}
if(l2!=null){
runner.next=l2;
}
return dummy.next;
}
}
题目很简单,自己先写了一下,竟然写的很复杂,后来看了别人的解法,确实聪明很多。继续加油!
本文介绍了一种简单高效的方法来合并两个已排序的链表。通过遍历两个链表并比较节点值,将较小的节点链接到新链表中,最终返回合并后的有序链表。
1480

被折叠的 条评论
为什么被折叠?



