假定用一個鏈表表示兩個數,其中每個節點僅包含一個數字。假設這兩個數的數字順序
排列,請設計一種方法將兩個數相加,並將其結果表現爲鏈表的形式。
給出 6->1->7
+ 2->9->5
。即,617 + 295
。
返回 9->1->2
。即,912
。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
l1 = ReverseList(l1);
l2 = ReverseList(l2);
int tmp = 0;
ListNode node = new ListNode(0);
ListNode p = node;
while (tmp != 0 || l1 != null || l2 != null) {
if (l1 != null) {
tmp += l1.val;
l1 = l1.next;
}
if (l2 != null) {
tmp += l2.val;
l2 = l2.next;
}
p.next = new ListNode(tmp % 10);
p = p.next;
tmp = tmp / 10;
}
return ReverseList(node.next);
}
public static ListNode ReverseList(ListNode head) {
if(head == null)
return null;
ListNode p = head;
ListNode q = p.next;
p.next = null;
while(q != null) {
head = q.next;
q.next = p;
p = q;
q = head;
}
head = p;
return head;
}
}