题目:
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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
题意:这是一道比简单的题,就是合并两个有序列表
但是由于我对java不熟,同时java没有指针这种东西,所以处理起来稍微费一点劲。
这里,我主要是通过将一条列表作为主列表,将另一个列表的元素依次插入。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
int flag=0;
ListNode header=l1;
ListNode pre=l1;
while(l1!=null&&l2!=null){
if(l1.val>=l2.val){
ListNode temp=new ListNode(0);
temp.val=l2.val;
if(flag==0){
temp.next=l1;
header=temp;
flag=1;
pre=header;
}
else{
pre.next=temp;
temp.next=l1;
pre=temp;
}
l2=l2.next;
}
else{
flag=1;
pre=l1;
l1=l1.next;
}
}
if(l2!=null){
pre.next=l2;
}
return header;
}
}