标签:函数 试题 构造函数 临时 ati first ext list ret
有序链表的构造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->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;
}
}
给出两个链表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;
}
标签:函数 试题 构造函数 临时 ati first ext list ret
原文地址:http://blog.51cto.com/devops2016/2310784