题目描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
解决方法
- 反转两个链表
- 同时遍历两个链表,依次相加生成新节点,并记录进位
- 反转新链表
==> 还可以简单进阶一下,不完全生成一条全新的链表。也就是说在任选一条链表基础上赋值结果,若判断少了节点,再新建,并直接连接在该链表后
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
head1 = reverse(head1);
head2 = reverse(head2);
ListNode ptail = new ListNode(-1);
ListNode phead = ptail, pnew = ptail;
int temp = 0; //进位
while (head1 != null || head2 != null || temp > 0) {
int num1 = (head1 == null ? 0 : head1.val);
int num2 = (head2 == null ? 0 : head2.val);
int num = num1 + num2 + temp;
pnew = new ListNode(num%10);
ptail.next = pnew;
ptail = ptail.next;
temp = num/10;
head1 = (head1 == null ? null : head1.next);
head2 = (head2 == null ? null : head2.next);
}
phead = reverse(phead.next);
return phead;
}
public ListNode reverse (ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode preNode = head;
ListNode target = head.next;
while (target != null) {
preNode.next = target.next;
target.next = head;
head = target;
target = preNode.next;
}
return head;
}
}
进阶
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
if (head1 == null || head2 == null) {
return head1 == null ? head2 : head1;
}
ListNode ptail = head2; //定位尾结点
head1 = reverse(head1);
head2 = reverse(head2);
ListNode phead = head2;
int temp = 0; //进位
while (head1 != null || head2 != null || temp > 0) {
int num1 = (head1 == null ? 0 : head1.val);
int num2 = (head2 == null ? 0 : head2.val);
int num = num1 + num2 + temp;
if (head2 != null) {
head2.val = num%10;
} else {
ptail.next = new ListNode(num%10);
ptail = ptail.next;
}
temp = num/10;
head1 = (head1 == null ? null : head1.next);
head2 = (head2 == null ? null : head2.next);
}
phead = reverse(phead);
return phead;
}
public ListNode reverse (ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode preNode = head;
ListNode target = head.next;
while (target != null) {
preNode.next = target.next;
target.next = head;
head = target;
target = preNode.next;
}
return head;
}
}