您的位置:首页 > 其它

Add Two Numbers II ---LeetCode

2016-11-23 21:19 323 查看
https://leetcode.com/problems/add-two-numbers-ii/

解题思路:

两种方法,第一种会改变链表结构,第二种不会。

反转链表法:先反转链表,然后计算结果,最后再反转结果。这将改变链表结构。

利用栈:定义两个栈,先将两个链表里的元素分别入栈,接着在 while 大循环里将元素依次相加,并维护进位。

solution 1 : Reverse

/**
* 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) {
l1 = reverse(l1);
l2 = reverse(l2);
return reverse(add(l1, l2));
}
public ListNode reverse(ListNode head) {
if(head == null)
return null;
ListNode prev = null;
while(head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public ListNode add(ListNode l1, ListNode l2) {
int digit = 0, carry = 0;
ListNode head = null, prev = null;
while(l1 != null && l2 != null) {
digit = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
ListNode newNode = new ListNode(digit);
if(head == null)
head = newNode;
else
prev.next = newNode;
prev = newNode;
l1 = l1.next; l2 = l2.next;
}
while(l1 != null) {
digit = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
ListNode newNode = new ListNode(digit);
if(head == null)
head = newNode;
else
prev.next = newNode;
prev = newNode;
l1 = l1.next;
}
while(l2 != null) {
digit = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
ListNode newNode = new ListNode(digit);
if(head == null)
head = newNode;
else
prev.next = newNode;
prev = newNode;
l2 = l2.next;
}
if(carry > 0) {
ListNode newNode = new ListNode(carry);
prev.next = newNode;
}
return head;
}
}


solution 2 : Stack

/**
* 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) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
int sum = 0;
ListNode next = new ListNode(0);
while(l1 != null) {
stack1.push(l1.val);
l1 = l1.next;
}
while(l2 != null) {
stack2.push(l2.val);
l2 = l2.next;
}
while(!stack1.isEmpty() || stack2.isEmpty()) {
if(!stack1.isEmpty())
sum += stack1.pop();
if(!stack2.isEmpty())
sum += stack2.pop();
next.val = sum % 10;
ListNode head = new ListNode(sum / 10);
head.next = next;
next = head;
sum /= 10;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: