2.Add Two Numbers-两个单链表相加

时间:2022-04-01 23:27:21

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. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;//定义两个指针变量 c1 c2
ListNode c2 = l2;
ListNode head = new ListNode(0);//定义一个新链表的头结点
ListNode d = head;//新链表的指针变量
int sum = 0;
while(c1 != null || c2 != null) {
if(c1 != null) {
sum = sum + c1.val;
c1 = c1.next;
}
if(c2 != null) {
sum = sum + c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum%10);
d = d.next;
sum = sum /10;
}
if(sum == 1) {
d.next = new ListNode(1);
}
return head.next; }
}