package newleedcode;
/**
* leetcode2.两数相加
* 两链表相加,逆序存放,首位为个位
*/
public class XLeedCode2 {
//链表结点
public static class ListNode{
int val;
ListNode next;
ListNode(){
next=null;
}
ListNode(int x){
val=x;
}
}
public ListNode addTwoNumber(ListNode l1,ListNode l2){
//初始化结点,数据域为0
ListNode dummyHead=new ListNode(0);
ListNode p=l1,q=l2,car=dummyHead;
int carry=0;
//通过while循环遍历链表并相加
while (p!=null||q!=null){
//三元操作符判断数据
int x=(p!=null)?p.val:0;
int y=(q!=null)?q.val:0;
int sum=carry+x+y;
//满10进1
carry=sum/10;
car.next= new ListNode(sum%10);
//进位
car=car.next;
//该位不为null即继续
if(p!=null)p=p.next;
if(q!=null)q=q.next;
if(carry>0){
car.next=new ListNode(carry);
}
}
return dummyHead.next;
}
public static void main(String args[]){
XLeedCode2 xLeedCode2=new XLeedCode2();
ListNode node=new ListNode(2);
ListNode node1=new ListNode(1);
node.next=new ListNode(9);
node1.next=new ListNode(3);
ListNode node3=xLeedCode2.addTwoNumber(node,node1);
while (node3!=null){
System.out.print(node3.val);
node3=node3.next;
}
}
}
/**哑结点
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**LeetCode提交代码
* class Solution {
* public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
* //初始化结点,数据域为0
* ListNode dummyHead=new ListNode(0);
* ListNode p=l1,q=l2,car=dummyHead;
* int carry=0;
* //通过while循环遍历链表并相加
* while (p!=null||q!=null){
* //三元操作符判断数据
* int x=(p!=null)?p.val:0;
* int y=(q!=null)?q.val:0;
* int sum=carry+x+y;
* //满10进1
* carry=sum/10;
* car.next= new ListNode(sum%10);
* //进位
* car=car.next;
* //该位不为null即继续
* if(p!=null)p=p.next;
* if(q!=null)q=q.next;
* if(carry>0){
* car.next=new ListNode(carry);
* }
* }
* return dummyHead.next;
* }
* }
*/