
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Numbers Represented as Linked Lists in Python
Suppose we have two singly linked list L1 and L2, each representing a number with least significant digits first, we have to find the summed linked list.
So, if the input is like L1 = [5,6,4] L2 = [2,4,8], then the output will be [7, 0, 3, 1, ]
To solve this, we will follow these steps:
carry := 0
res := a new node with value 0
curr := res
-
while L1 is not empty or L2 is not empty or carry is non-zero, do
l0_val := value of L1 if L1 is not empty otherwise 0
l1_val := value of L2 if L2 is not empty otherwise 0
sum_ := l0_val + l1_val
carry := quotient of (sum_ + carry) / 10
add_val := remainder of (sum_ + carry) / 10
curr.next := a new node with value add_val
curr := next of curr
L1 := next of L1 if L1 is not empty otherwise null
L2 := next of L2 if L2 is not empty otherwise null
next of curr := null
return next of res
Let us see the following implementation to get better understanding:
Example
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return head def print_list(head): ptr = head print('[', end = "") while ptr: print(ptr.val, end = ", ") ptr = ptr.next print(']') class Solution: def solve(self, L1, L2): carry = 0 res = ListNode(0) curr = res while L1 or L2 or carry: l0_val = L1.val if L1 else 0 l1_val = L2.val if L2 else 0 sum_ = l0_val + l1_val carry, add_val = divmod(sum_ + carry, 10) curr.next = ListNode(add_val) curr = curr.next L1 = L1.next if L1 else None L2 = L2.next if L2 else None curr.next = None return res.next ob = Solution() L1 = make_list([5,6,4]) L2 = make_list([2,4,8]) print_list(ob.solve(L1, L2))
Input
[5,6,4], [2,4,8]
Output
[7, 0, 3, 1, ]