做题记录
solution1:直接计算出l1和l2数据之和,然后构造链表,这种情况可能会越界,因为列表的长度最长可以为100
solution2:反转列表,然后从个位开始逐个相加
solution3:不反转,使用栈
使用solution2的思想实现了
第一步:借助24题的实现反转l1和l2,p和q指针分别指向反转之后的l1和l2的首节点;
第二步:构造变量catch,用来存储进位,在p != null 或者q != null 或者catch != 0的情况下计算节点数值和进位的和sum;
第三步:构造节点ListNode pre= null,以便后续把节点连接起来。
第四步:计算出当前的进位catch和进位之后的数值sum,并构造节点ListNode cur = new ListNode(sum).
并且将cur.next指向pre,将pre指向next
第五步:循环结束之后,pre所指向的节点就是最高位数据的节点,直接返回即可。
备注:
- 第一次写代码的时候,把sum值放在while循环的外面造成错误的结果,实际上sum应该放在while循环的里边,不能影响下一次的sum值。而catch对下一次的数值之和有影响,所以需要放在while循环的外面。
- while的循环的条件有一条是catch!=0,这一条不要遗漏!
附上代码:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
int count = 0;
ListNode pre = null;
while (l1 != null || l2 != null || count != 0) {
int num = count;
if (l1 != null) {
num += l1.val;
l1 = l1.next;
}
if (l2 != null) {
num += l2.val;
l2 = l2.next;
}
count = num / 10;
num = num % 10;
ListNode cur = new ListNode(num);
cur.next = pre;
pre = cur;
}
return pre;
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = null;
ListNode cur = head;
ListNode next = head.next;
while (next != null) {
cur.next = pre;
pre = cur;
cur = next;
next = next.next;
}
cur.next = pre;
return cur;
}