The Indian Engineer

Problem 2816 Double a Number Represented as a Linked List

Posted on 3 mins

Linked-List Cpp Stack Pointers

Problem Statement

Link - Problem 2816

Question

You are given the head of a non-empty linked list representing a non-negative integer without leading zeroes.

Return the head of the linked list after doubling it

Example 1

Input: head = [1,8,9]
Output: [3,7,8]
Explanation: The figure above corresponds to the given linked list which represents the number 189.
            Hence, the returned linked list represents the number 189 * 2 = 378.

Example 2

Input: head = [9,9,9]
Output: [1,9,9,8]
Explanation: The figure above corresponds to the given linked list which represents the number 999.
             Hence, the returned linked list reprersents the number 999 * 2 = 1998.

Constraints

Solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* doubleIt(ListNode* head) {
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        stack<ListNode*>st;
        ListNode* temp = head;
        while(temp!=nullptr)
        {
            st.push(temp);
            temp=temp->next;
        }

        int carry = 0, newVal = 0;
        while(!st.empty())
        {
            temp = st.top();
            st.pop();
            newVal = 2*temp->val + carry;
            carry = newVal/10;
            newVal = newVal%10;
            //cout<<carry<<newVal<<endl;
            temp->val = newVal;
        }
        if(carry)
        {
            ListNode* newhead = new ListNode(carry,head);
            return newhead;
        }

        return head;
    }
};

Complexity

Explanation

1. Intuition

2. Implementation


This is a problem where FIFO principle of stack is used to reverse the linkedlist without manipulating any pointers.