问题描述:
/**
* 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.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
*
* Output: 7 -> 0 -> 8
*/
就是说有两个链表代表两个非负的整数,每一个链表节点都存储一个单个的数字,并且节点存储的顺序和整数的数字排列顺序是相反的,如上所示,数a为342,数b为465,相加为807.
解题思想还是从数的末尾开始相加,对于这道题来说也就是从两个链表的开头进行运算,期间要声明一个变量来作为进位。
这道题和我前面一篇博客是类似的,在进行运算时要对两个数“对齐”,即在对齐的情况下是一种运算,不对齐又是另一种情况。下面是代码:
public class AddTwoNumbers {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode head = new ListNode(0);
ListNode cur = head;
int plus = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + plus;
plus = sum / 10;
sum = sum % 10;
cur.next = new ListNode(sum);
cur = cur.next;
l1 = l1.next;
l2 = l2.next;
}
if (l1 != null) {
if (plus != 0) {
cur.next = addTwoNumbers(l1, new ListNode(plus));
} else {
cur.next = l1;
}
} else if (l2 != null) {
if (plus != 0) {
cur.next = addTwoNumbers(l2, new ListNode(plus));
} else {
cur.next = l2;
}
} else if (plus != 0) {
cur.next = new ListNode(plus);
}
return head.next;
}
public static void main(String args[])
{
ListNode l1=new ListNode(2);
l1.next=new ListNode(4);
l1.next.next=new ListNode(3);
ListNode r1=new ListNode(5);
r1.next=new ListNode(6);
r1.next.next=new ListNode(4);
ListNode newnode=addTwoNumbers(l1,r1);
while(newnode!=null)
{
System.out.println(newnode.val);
newnode=newnode.next;
}
}
}
在声明Listnode时,竟然感觉有点吃力,忘了数据结构是怎么样的了,然后查了一下才解决,其实,用java声明单链表是很简单的,如下所示:
public class ListNode {
int val;
ListNode next;
public ListNode(int x){
val = x;
next = null;
}
}