Add Two Numbers

本文介绍了一种使用链表表示非负整数并进行加法运算的方法。提供了两种解决方案:一种直接遍历链表节点,另一种利用栈来实现不反转链表的加法。通过这两种方法,有效地解决了链表加法问题。

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;
* next = null;
* }
* }
*/


public
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); ListNode p = head; int carry = 0; while(l1 != null || l2 != null){ int result = 0; int va = (l1 == null)? 0: l1.val; int vb = (l2 == null)? 0: l2.val; result = (va+vb+carry)%10; carry = (va+vb+carry)/10; p.next = new ListNode(result); p = p.next; l1 = (l1 == null ? null : l1.next); l2 = (l2 == null ? null : l2.next); } if(carry != 0){ p.next = new ListNode(carry); } return head.next; } }

 

stack 解法,不 reverse list

 1 public static ListNode addTwoNumber(ListNode l1, ListNode l2){
 2         Stack<Integer> s1 = new Stack<Integer>();
 3         Stack<Integer> s2 = new Stack<Integer>();        
 4         
 5         ListNode fake = new ListNode(Integer.MIN_VALUE);
 6         
 7         ListNode runner = l1;
 8         while(runner != null){
 9             s1.push(runner.val);
10             runner = runner.next;
11         }
12         
13         runner = l2;
14         while(runner != null){
15             s2.push(runner.val);
16             runner = runner.next;
17         }
18         
19         runner = fake;
20         int carry = 0;
21         while(!s1.empty() || !s2.empty()){
22             int v1 = (s1.empty()? 0: s1.pop());
23             int v2 = (s2.empty()? 0: s2.pop());
24             int d = v1+v2+carry;
25             carry = d/10;
26             runner.next = new ListNode(d%10);
27             runner =runner.next;
28         }
29         
30         if(carry != 0){
31             runner.next = new ListNode(carry);
32         }
33         
34         // reverse the result list
35         ListNode head = fake.next;
36         fake.next = null;
37         ListNode slow = head, fast = head.next, tmp = null;
38         while(fast != null){
39             tmp = fast.next;
40             fast.next = slow;
41             slow = fast;
42             fast = tmp;
43         }
44         head.next = null;
45         
46         
47         return slow;
48     }
49     

 

转载于:https://www.cnblogs.com/RazerLu/p/3532649.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值