-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2_Add_Two_Numbers.java
More file actions
73 lines (65 loc) · 1.83 KB
/
Copy path2_Add_Two_Numbers.java
File metadata and controls
73 lines (65 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* 2. Add Two Numbers
* 2019-05-31 Runtime: 2 ms
* Target: Two linked lists, the numbers on the nodes are reversed, forming numbers, sums, and return lists
* Difficulty:Medium
* Classification:Linked List, Math
* Algorithm: Traversing the two linked lists at the same time, one-to-one bitwise addition.
* Note that the carry could be 0 or 1;
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
ListNode p = l1, q = l2;
int carry = 0;
while(p != null || q != null){
int x = (p != null) ? p.val:0;
int y = (q != null) ? q.val:0;
int sum = x + y + carry;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if(p != null) p = p.next;
if(q != null) q = q.next;
}
if(carry > 0){
curr.next = new ListNode(carry);
}
return dummy.next;
}
}
/// follow up: the linked list order reverse, calculate sum
//////////sol 1
public ListNode reverseList(ListNode head)
{
if (head == null) return null;
ListNode pre = null;
ListNode next;
while (head != null) {
next = head->next;
head->next = pre;
pre = head;
head = next;
}
return pre;
}
//////////sol 2: recursion
public ListNode reverseListRecursion(ListNode head) {
ListNode newHead;
if (head == null || head.next == null) {
return head;
}
newHead = reverseListRecursion(head.next);
head.next.next = head;
head.next = null;
return newHead;
}