-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.两数相加.java
83 lines (67 loc) · 1.77 KB
/
2.两数相加.java
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
74
75
76
77
78
79
80
81
82
/*
* @lc app=leetcode.cn id=2 lang=java
*
* [2] 两数相加
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode sum = l1;
ListNode last = sum;
while (last != null) {
if (last != l2)
last.val += l2.val;
if (last.val >= 10) {
last.val %= 10;
if (last.next == null)
if (l2.next != null)
last.next = l2.next;
else {
ListNode newnode = new ListNode(1, null);
last.next = newnode;
}
last.next.val += 1;
}
last = last.next;
l2 = l2.next;
}
return sum;
}
public ListNode reverse(ListNode list) {
/*快慢结点*/
ListNode node1 = list;
//只有一个结点
if (list.next == null)
return node1;
//只有两个结点
ListNode node2 = list.next;
if (node2.next == null) {
node1.next = null;
node2.next = node1;
return node2;
}
//三个结点及以上
ListNode node3 = node2.next;
node1.next = null;
while (node3.next != null) {
node2.next = node1;
node1 = node2;
node2 = node3;
node3 = node3.next;
}
node2.next = node1;
node3.next = node2;
return node3;
}
}
// @lc code=end