-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode_0002.py
67 lines (52 loc) · 2.04 KB
/
leetcode_0002.py
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
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def navigation(self, l):
if l == None:
return ""
return str(l.val) + self.navigation(l.next)
# Function to create a linked list from a list of values
def create_linked_list(self, values):
if not values:
return None # Return None if the list is empty
head = ListNode(values[0]) # Create the head node
current = head
for value in values[1:]:
current.next = ListNode(value) # Create and link the next node
current = current.next
return head
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
val1 = self.navigation(l1)
val2 = self.navigation(l2)
result = str(int(val1[::-1]) + int(val2[::-1]))
print(result[::-1])
return self.create_linked_list(list(result[::-1]))
s = Solution()
# Create the linked list from the list of values
head1 = s.create_linked_list([2, 4, 9])
head2 = s.create_linked_list([5, 6, 4, 9])
s.addTwoNumbers(head1, head2)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# class Solution:
# def navigation(self, l1: Optional[ListNode]) -> str:
# if not l1:
# return ''
# return str(l1.val) + self.navigation(l1.next)
# def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# num1 = self.navigation(l1)[::-1]
# num2 = self.navigation(l2)[::-1]
# result = str(int(num1) + int(num2))[::-1]
# head = ListNode(int(result[0])) # Create the head node
# current = head
# for value in result[1:]:
# current.next = ListNode(int(value)) # Create and link the next node
# current = current.next
# return head