版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cjh_android/article/details/84071512
题目
你将获得两个非空链表,表示两个非负整数。 数字以相反的顺序存储,每个节点包含一个数字。 使这两个数字相加并将其结果作为链表返回。
你可以认为这两个数字不包含任何0开头的数字,除了数字0本身。
举例
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析
其实代码比较简单,这条题目难点反而在于读懂题目…
题目中有说道,数字是以相反的顺序存储进链表的:
那么上面的例子中的两个链表其实代表的分别是 342 和 465 这两个数字:342 + 465 = 807;
当然也要考虑到两个链表长度不同的情况!
另外题目中也明确说明了每个节点只包含了一个数字,就是说 ListNode.content < 10!
其实这条题目,思路很简单,更多的是考察的是代码能力,以及边界考虑情况。
代码
代码测试了下面几组数据
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Input: (2 -> 4 -> 3 -> 5) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8 -> 5
Input: (9 -> 9 -> 9) + (1 -> 1 -> 1)
Output: 0 -> 1 -> 1 -> 1
Input: (9 -> 9 -> 9 -> 5) + (1 -> 1 -> 1)
Output: 0 -> 1 -> 1 -> 6
Input: (9 -> 9 -> 9 -> 9) + (1 -> 1 -> 1)
Output: 0 -> 1 -> 1 -> 0 -> 1
package algorithm011;
import algorithm006.ListNode;
public class Algorithm011 {
public static void main(String[] args) {
System.out.println(sum(getTest1(), getTest2()));
}
/**
* 思路:设置 flag,如果flag为true,就递增1
* 设置 headNode 作为返回链表的额头
* 设置 preSum,当循环结束,对最后的flag做处理
*
* @param a
* @param b
* @return
*/
public static ListNode sum(ListNode a, ListNode b) {
if(null == a) return b;
if(null == b) return a;
ListNode sum = null;
ListNode headNode = null;
ListNode preSum = null;
boolean flag = false;
while(a != null || b != null) {
int content = -1;
if(a != null && b != null) {
content = a.content + b.content;
a = a.next;
b = b.next;
}else if(a != null) {
content = a.content;
a = a.next;
}else {
content = b.content;
b = b.next;
}
if(flag)
content+=1;
if(content >=10) {
content-=10;
flag = true;
}else
flag = false;
if(sum == null)
sum = new ListNode(content);
else
sum.content = content;
if(headNode == null)
headNode = sum;
sum.next = new ListNode(0);
preSum = sum;
sum = sum.next;
}
if(flag)
sum.content += 1;
else
preSum.next = null;
return headNode;
}
public static ListNode getTest1() {
ListNode listNode2 = new ListNode(9);
ListNode listNode4 = new ListNode(9);
ListNode listNode6 = new ListNode(9);
ListNode listNode8 = new ListNode(9);
listNode2.next = listNode4;
listNode4.next = listNode6;
listNode6.next = listNode8;
return listNode2;
}
public static ListNode getTest2() {
ListNode listNode2 = new ListNode(1);
ListNode listNode4 = new ListNode(1);
ListNode listNode6 = new ListNode(1);
listNode2.next = listNode4;
listNode4.next = listNode6;
return listNode2;
}
}