描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
输出
{1,0,0,0}
思路
把链表反转再相加, 最后把相加的结果再反转即可。
比如上面的链表1 反转就是 739 , 链表2反转就是 36 相加就是0001 ,反转就是1000
其实就是模拟我们加法过程。
public class Solution {
// 链表反转
public ListNode reverseList(ListNode head){
if(head == null || head.next == null)
return head;
ListNode last = null;
ListNode tmp = null;
while(head != null){
tmp = head.next;
head.next = last;
last = head;
head = tmp;
}
return last;
}
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
head1 = reverseList(head1);
head2 = reverseList(head2);
ListNode p1 = head1;
ListNode p2 = head2;
int value = 0;
int jinwei = 0;
ListNode res = new ListNode(-1);
ListNode m_res = res;///虚拟头节点
while(p1 != null && p2 !=null){
value = (p1.val + p2.val+ jinwei ) % 10;
jinwei = (p1.val + p2.val + jinwei) / 10;
res.next = new ListNode(value);
res =res.next;
p1 = p1.next;
p2 = p2.next;
}
while (p1 != null){
value = (p1.val + jinwei) % 10;
jinwei = (p1.val + jinwei) / 10;
res.next = new ListNode(value);
res = res.next;
p1 = p1.next;
}
while(p2 != null){
value = (p2.val + jinwei) % 10;
jinwei = (p2.val + jinwei) / 10;
res.next = new ListNode(value);
res =res.next;
p2 = p2.next;
}
if(jinwei != 0){
res.next = new ListNode(jinwei);
}
return reverseList(m_res.next);
}
public static void main(String[] args) {
ListNode head1 = new ListNode(9);
ListNode a = new ListNode(3);
ListNode b = new ListNode(7);
head1.next = a;
a.next = b;
ListNode head2 = new ListNode(6);
ListNode c = new ListNode(3);
head2.next = c;
Solution s = new Solution();
ListNode res = s.addInList(head1, head2);
int num = 1;
while (res != null){
// System.out.println(res.val);
System.out.printf("第 %d 个节点: %d \n", num++, res.val);
res = res.next;
}
// System.out.println(a);
}
}