Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1
Add Number Linked Lists
Difficulty: Medium Accuracy: 34.52%
You are given the head of two singly linked lists head1 and head2 representing two non-negative integers. You have to return the head of the linked list representing the sum of these two numbers.
Note: There can be leading zeros in the input lists, but there should not be any leading zeros in the output list.
Examples:
Input:
Output: 1 -> 1 -> 2 -> 2
Explanation: Given numbers are 123 and 999. There sum is 1122.
Input:

Output: 7 -> 0
Explanation: Given numbers are 63 and 7. There sum is 70.
Constraints:
1 β€ Number of nodes in head1, head2 β€ 105
0 β€ node->data β€ 9
Solution:
class Solution:
def reverse(self, head):
prev = None
while head:
nxt = head.next
head.next = prev
prev = head
head = nxt
return prev
def addTwoLists(self, head1, head2):
h1 = self.reverse(head1)
h2 = self.reverse(head2)
carry = 0
dummy = Node(0)
curr = dummy
while h1 or h2 or carry:
s = carry
if h1:
s += h1.data
h1 = h1.next
if h2:
s += h2.data
h2 = h2.next
curr.next = Node(s % 10)
curr = curr.next
carry = s // 10
res = self.reverse(dummy.next)
while res and res.data == 0 and res.next:
res = res.next
return res
Top comments (0)