File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ var reverseList = function ( head ) {
2+ if ( ! head ) return null
3+ let res = null
4+ let dfs = function ( node ) {
5+ if ( node . next ) {
6+ dfs ( node . next )
7+ node . next . next = node
8+ } else {
9+ res = node
10+ }
11+ }
12+
13+ dfs ( head )
14+
15+ head . next = null
16+
17+ return res
18+ } ;
19+
20+ var addTwoNumbers = function ( l1 , l2 ) {
21+ l1 = reverseList ( l1 )
22+ l2 = reverseList ( l2 )
23+
24+ let i = 0
25+ let root = new ListNode ( )
26+ let cur = root
27+ let plus = false
28+
29+ let traverse = ( node1 , node2 ) => {
30+ let isDouble = ! ! node2
31+ while ( isDouble ? ( node1 && node2 ) : node1 ) {
32+ cur . next = new ListNode ( )
33+ cur = cur . next
34+
35+ let sum = node1 . val + ( plus ? 1 : 0 )
36+ if ( isDouble ) {
37+ sum += node2 . val
38+ }
39+
40+ if ( sum >= 10 ) {
41+ sum %= 10
42+ plus = true
43+ } else {
44+ plus = false
45+ }
46+ cur . val = sum
47+
48+ node1 = node1 . next
49+ if ( isDouble ) {
50+ node2 = node2 . next
51+ }
52+ }
53+
54+ if ( node1 ) {
55+ traverse ( node1 )
56+ }
57+ if ( node2 ) {
58+ traverse ( node2 )
59+ }
60+ }
61+
62+ traverse ( l1 , l2 )
63+
64+ if ( plus ) {
65+ cur . next = new ListNode ( 1 )
66+ }
67+
68+ return reverseList ( root . next )
69+ } ;
You can’t perform that action at this time.
0 commit comments