劍指offer——(9)合併兩個排序的連結串列
阿新 • • 發佈:2018-11-30
/* 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; ListNode newLN = null; ListNode T = null; //合併後的新連結串列 int temp = 0; boolean boo = false; //判斷返回連結串列的第一個節點 while(list1!=null||list2!=null){ temp = 0; if(list1!=null&&list2!=null){ temp = list1.val<=list2.val?list1.val:list2.val; if(temp==list1.val) list1 = list1.next; else list2 = list2.next; } else if(list1!=null){ temp = list1.val; list1 = list1.next; } else { temp = list2.val; list2 = list2.next; } if(boo==false) { newLN = new ListNode(temp); T = newLN; boo = true; } newLN = (newLN.next = new ListNode(temp)); } /*while(T.next!=null) { System.out.print(T.next.val+" "); T = T.next; }*/ //System.out.println(); return T.next; } }