合并两个有序链表
题目如下
代码如下
/** * Definition for singly-linked list.
* public class ListNode
* {
* *
* public int val;
* * public ListNode next;
* * public ListNode(int x) { val = x;
* }
* * }
* */public class Solution
* {
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
ListNode result=new ListNode(-1);
ListNode l3 = result;
while (l1 != null && l2 != null)
{
if (l1.val < l2.val)
{
l3.next = l1;
l1 = l1.next;
}
else
{
l3.next = l2;
l2 = l2.next;
}
l3 = l3.next;
}
if (l1 == null)
l3.next = l2;
if (l2 == null)
l3.next = l1;
return result.next;
}}
解题心得
通过链表指针的移动,对两个链表进行比较,按照从小到大的顺序输出。同时若其中一个链表比另一个链表长度小,则将剩下的位置连接到新链表的后面。