Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Node *multipleTwoNumbersRepresentedByLinkedList(Node *headOne, Node *headTwo)
- {
- Node newDummyHead(INT_MAX);
- Node *tailOfNewList = &newDummyHead;
- // all edge cases
- if (!headOne || !headTwo)
- return nullptr;
- if (!(headOne->next) && headOne->val == 0)
- return new Node(0);
- if (!(headTwo->next) && headTwo->val == 0)
- return new Node(0);
- // First of all: reverse both linkedlists
- headOne = reverseLinkedList(headOne);
- headTwo = reverseLinkedList(headTwo);
- Node *travelerOne = headOne;
- Node *travelerTwo = headTwo;
- int currentValueOfMultiplication = 0;
- int currentCarryOfMultiplication = 0;
- int currentValueOfAddition = 0;
- int currentCarryOfAddition = 0;
- int level = 1; // first level is '1'
- while (travelerTwo)
- {
- // reset before trying new multiplication
- tailOfNewList = &newDummyHead;
- travelerOne = headOne;
- currentCarryOfMultiplication = 0;
- currentCarryOfAddition = 0;
- for (int i = 0; i + 1 < level; ++i) // we are advancing level - 1 times here to consider the level everytime we start new level:
- {
- tailOfNewList->next = tailOfNewList->next ? tailOfNewList->next : new Node(0);
- tailOfNewList = tailOfNewList->next;
- }
- while (travelerOne)
- {
- tailOfNewList->next = tailOfNewList->next ? tailOfNewList->next : new Node(0);
- tailOfNewList = tailOfNewList->next;
- currentValueOfMultiplication = travelerOne->val * travelerTwo->val + currentCarryOfMultiplication;
- currentCarryOfMultiplication = currentValueOfMultiplication / 10;
- currentValueOfMultiplication %= 10;
- tailOfNewList->val = tailOfNewList->val + currentValueOfMultiplication + currentCarryOfAddition;
- currentCarryOfAddition = tailOfNewList->val / 10;
- tailOfNewList->val %= 10;
- travelerOne = travelerOne->next;
- }
- travelerTwo = travelerTwo->next;
- ++level;
- }
- if (currentCarryOfAddition != 0)
- {
- tailOfNewList->next = new Node(currentCarryOfAddition);
- }
- return reverseLinkedList(newDummyHead.next);
- }
- Node *reverseLinkedList(Node *head)
- {
- Node *prev, *curr, *next;
- prev = nullptr;
- curr = head;
- while (curr)
- {
- next = curr->next;
- curr->next = prev;
- prev = curr;
- curr = next;
- }
- return prev;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement