letcode里面刷题,坑还是链表不熟,(1)头结点还是有必要设置,否则返回的时候找不到位置;(2)先设置next到新节点再next到下一个节点;都是基础知识
/*
*
* You are given two linked lists representing two non-negative numbers.
* The digits are stored in reverse order and each of their nodes contain a single digit.
* Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
* */
class CONF{
public static final int initialVal=-1;
} class ListNode {
int val=CONF.initialVal;
ListNode next=null;
ListNode(int x) { val = x; }
ListNode(){};
} public class addTwoNumber {
public ListNode add(ListNode l1, ListNode l2) {
ListNode resHeadNode = new ListNode();
ListNode leftNode = l1.next,rightNode = l2.next,resNode=resHeadNode;
int addon=0;
while(leftNode!=null){
ListNode tmpNode=new ListNode((leftNode.val+rightNode.val)%10+addon);
addon=(leftNode.val+rightNode.val)/10;
resNode.next=tmpNode;
resNode=resNode.next;
leftNode = leftNode.next;
rightNode= rightNode.next;
}
return resHeadNode;
}
public void initList(String[] vals,ListNode headList){
ListNode valList=headList;
for(int i=0;i<vals.length;i++){
ListNode tmpnode=new ListNode(Integer.valueOf(vals[i]));
valList.next=tmpnode;
valList=valList.next;
}
}
public static void printList(ListNode headList){
ListNode resNode=headList.next;
while(resNode!=null){
System.out.println("res:"+resNode.val);
resNode = resNode.next;
}
}
public static void main(String[] args){
addTwoNumber instance =new addTwoNumber();
ListNode leftList=new ListNode();
ListNode rightList=new ListNode();
instance.initList(new String[]{"2","4","3"},leftList);
instance.initList(new String[]{"5","6","4"},rightList);
System.out.println("leftList:");
printList(leftList);
System.out.println("rightList:");
printList(rightList);
ListNode resNodeList=instance.add(leftList,rightList);
System.out.println("resNodeList:");
printList(resNodeList);
}
}