Add Two Numbers

Let’s discuss a problem add two numbers as lists and their java code.

Given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. We have to write a code to add these two numbers and return the sum as a linked list.

For this problem, you may assume the two numbers do not contain any leading zero, except the number 0 itself.

For example –

Linked List 1 : 2 -> 4 -> 6 -> NULL

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

Result : 7 -> 0 -> 1 -> 1 -> NULL

Explanation :

In this example first, we added 2 and 5 the result is 7. Then, 6 and 4 the result is 10, so we put 0 and take 1 as a carry. Then, we added 6, 4, and 1 (carry) the result is 11, so we put 1 and take 1 as a carry.

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.

Odd Even Linked List

In this tutorial, I am going to discuss a programming question how to segregate even and odd nodes in a linked list or odd even linked list.

Given a singly linked list, We have to write a code to group all odd nodes together followed by the even nodes. We have to group based on node number not the value present in the node.

Try to solve this problem in O(n) time complexity and O(1) space complexity where n is the no. of nodes in a linked list.

Also, the relative order inside both the even and odd groups should remain as it was in the input. The first node is considered odd, the second node even and so on …

For example –

In the this example, Given input linked list is

1 -> 2 -> 3 -> 4 -> NULL

When we segregate even and odd nodes in a Linked List then the output is

1 -> 3 -> 2 -> 4 -> NULL