有序鏈表基礎和面試題
阿新 • • 發佈:2018-10-30
system 構造函數 null 打印 lis 有序鏈表 out st2 有序鏈表合並 有序鏈表的構造
class ListNode{ int val; ListNode nextNode; // 構造函數 ListNode(int val){ this.val=val; this.nextNode=null; } } public static ListNode buildListNode(int [] list){ //創建3個臨時的ListNode ListNode first=null,last=null,newNode; for(int i=0;i<list.length;i++){ newNode=new ListNode(list[i]); if(first==null){ first=newNode; last=newNode; }else{ last.nextNode=newNode; last=newNode; } } return first; }
有序鏈表的簡單打印:
int[] a=new int[]{1,5,6};
ListNode alist=buildListNode( a);
ListNode testnode = alist;
while(testnode != null) {
System.out.println("-->" + testnode.val);
testnode=testnode.nextNode;
}
-->1-->5-->6
面試題1:
將兩個有序鏈表合並為一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。 示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = null; if (l1.val <= l2.val){ head = l1; head.next = mergeTwoLists(l1.next, l2); } else { head = l2; head.next = mergeTwoLists(l1, l2.next); } return head; } }
面試題2:
給出兩個鏈表3->1->5->null 和 5->9->2->null,返回8->0->8->null
public static ListNode addList(ListNode list1,ListNode list2){
ListNode pre=null;
ListNode last=null,newNode=null;
ListNode result=null;
int val=0;
int carry=0;
while(list1!=null||list2!=null){
val=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)%10;
carry=((list1==null?0:list1.val)+(list2==null?0:list2.val)+carry)/10;
list1=list1==null?null:list1.nextNode;
list2=list2==null?null:list2.nextNode;
newNode=new ListNode(val);
if(pre==null){
pre=newNode;
last=newNode;
}else{
last.nextNode=newNode;
last=newNode;
}
}
if(carry>0){
newNode=new ListNode(carry);
last.nextNode=newNode;
last=newNode;
}
return pre;
}
有序鏈表基礎和面試題