Skip to content

Commit 0a9d4f4

Browse files
committed
Add two numbers represented by linked lists
1 parent ea3f39e commit 0a9d4f4

File tree

1 file changed

+140
-0
lines changed

1 file changed

+140
-0
lines changed
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
"""
2+
Problem Link: https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1
3+
4+
Given two numbers represented by two linked lists of size N and M. The task is to return a sum list.
5+
The sum list which is a linked list representation of addition of two input numbers.
6+
7+
Input:
8+
First line of input contains number of testcases T. For each testcase, first line of input
9+
contains length of first linked list and next line contains N elements of the linked list.
10+
Again, next line contains M, and following line contains M elements of the linked list.
11+
12+
Output:
13+
Output the resultant linked list.
14+
15+
User Task:
16+
The task is to complete the function addTwoLists() which has node reference of both the
17+
linked lists and returns the head of new list.
18+
19+
Constraints:
20+
1 <= T <= 100
21+
1 <= N, M <= 100
22+
23+
Example:
24+
Input:
25+
2
26+
2
27+
4 5
28+
3
29+
3 4 5
30+
2
31+
6 3
32+
1
33+
7
34+
35+
Output:
36+
0 9 3
37+
0 7
38+
39+
Explaination:
40+
5->4 // linked list repsentation of 45.
41+
5->4->3 // linked list representation of 345.
42+
0->9 ->3 // linked list representation of 390 resultant linked list.
43+
"""
44+
import atexit
45+
import io
46+
import sys
47+
_INPUT_LINES = sys.stdin.read().splitlines()
48+
input = iter(_INPUT_LINES).__next__
49+
_OUTPUT_BUFFER = io.StringIO()
50+
sys.stdout = _OUTPUT_BUFFER
51+
@atexit.register
52+
def write():
53+
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
54+
55+
# Node Class
56+
class Node:
57+
def __init__(self, data): # data -> value stored in node
58+
self.data = data
59+
self.next = None
60+
# Linked List Class
61+
class LinkedList:
62+
def __init__(self):
63+
self.head = None
64+
# creates a new node with given value and appends it at the end of the linked list
65+
def append(self, new_value):
66+
new_node = Node(new_value)
67+
if self.head is None:
68+
self.head = new_node
69+
return
70+
curr_node = self.head
71+
while curr_node.next is not None:
72+
curr_node = curr_node.next
73+
curr_node.next = new_node
74+
# prints the elements of linked list starting with head
75+
def printList(head):
76+
if head is None:
77+
print(' ')
78+
return
79+
curr_node = head
80+
while curr_node:
81+
print(curr_node.data,end=" ")
82+
curr_node=curr_node.next
83+
print(' ')
84+
if __name__ == '__main__':
85+
t=int(input())
86+
for cases in range(t):
87+
n_a = int(input())
88+
a = LinkedList() # create a new linked list 'a'.
89+
nodes_a = list(map(int, input().strip().split()))
90+
nodes_a = nodes_a[::-1] # reverse the input array
91+
for x in nodes_a:
92+
a.append(x) # add to the end of the list
93+
n_b =int(input())
94+
b = LinkedList() # create a new linked list 'b'.
95+
nodes_b = list(map(int, input().strip().split()))
96+
nodes_b = nodes_b[::-1] # reverse the input array
97+
for x in nodes_b:
98+
b.append(x) # add to the end of the list
99+
result_head = addBoth(a.head,b.head)
100+
printList(result_head)
101+
''' This is a function problem.You only need to complete the function given below '''
102+
#User function Template for python3
103+
'''
104+
Function to add two numbers represented
105+
in the form of the linked list.
106+
107+
Function Arguments: head_a and head_b (heads of both the linked lists)
108+
Return Type: head of the resultant linked list.
109+
110+
__>IMP : numbers are represented in reverse in the linked list.
111+
Ex:
112+
145 is represented as 5->4->1.
113+
114+
resultant head is expected in the same format.
115+
116+
# Node Class
117+
class Node:
118+
def __init__(self, data): # data -> value stored in node
119+
self.data = data
120+
self.next = None
121+
'''
122+
def addBoth(head_a,head_b):
123+
#code here
124+
res = Node(0)
125+
cur = res
126+
carry = 0
127+
while head_a or head_b:
128+
x = head_a.data if head_a else 0
129+
y = head_b.data if head_b else 0
130+
summ = carry + x + y
131+
carry = summ // 10
132+
cur.next = Node(summ%10)
133+
cur = cur.next
134+
if head_a:
135+
head_a = head_a.next
136+
if head_b:
137+
head_b = head_b.next
138+
if carry > 0:
139+
cur.next = Node(carry)
140+
return res.next

0 commit comments

Comments
 (0)