/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { if(list1==null&&list2==null) return null; else if(list1==null) return list2; else if(list2==null) return list1; //两个链表的头指针 head1为最终链表的起点 ListNode head1,pre1,pre2; head1=(list1.val)<(list2.val)?list1:list2; //pre1,pre2分别为两个链表中为加入链表的首个元素 pre1=head1.next; pre2=(list1.val)<(list2.val)?list2:list1; ListNode head=head1; //head为当前访问的指针,新链表每加入一个元素,head=head->next while(pre1!=null) { if(pre2==null) {head.next=pre1; break;} //当另一条链表全部加入新链表时,直接退出 if(pre1.val<pre2.val) { head.next=pre1; pre1=pre1.next; }else { head.next=pre2; pre2=pre2.next; } head=head.next; } if(pre2!=null) head.next=pre2; //如果链表2还有元素(链表1全部加入)则加入剩余的链表2 return head1; } }
变量命名不是很规范