Add Two Numbers – II

Let’s discuss a very interesting problem add two numbers represented by linked lists.

Problem Statement

Given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and least significant digit comes last. Each of the linked list node contain a single digit.

We have to write a code to add the two numbers and return it as a linked list.

Both the numbers do not contain any leading zero, except the number 0 itself.

NOTE: Reversing a linked list is not allowed.

For Example –

List 1 : 7 -> 2 -> 4 -> 3 -> NULL

List 2 : 5 -> 6 -> 4 -> NULL

Result : 7 -> 8 -> 0 -> 7 -> NULL

Explanation : The first linked list is representing the number 7243 and the second linked is representing the number 564. If we add these two numbers we get 7807, which we have to return in the form of a linked list.

Add Two Numbers Represented By Linked Lists

We have discussed the problem statement. In this problem, reversing a list is not allowed. How do we add the numbers represented by two linked lists? Do we need any additional data structure for solving this problem.

Programming questions on linked list

Programming Video Tutorials

Add Two Numbers Represented By Linked Lists – Java Code

To solve this problem, Here i am using additional data structure stack.

The addition of numbers will start from the least significant digit and it is present at the end of the list. The idea here is two use two stacks, first we traverse both the lists and put the node values in a stack.

Then we run a loop until any of the stack is not empty and we do the addition and create a result linked list.

Check if a linked list is palindrome or not

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.