node* calculateSumForward(node* a, node* b) { int lenA = countNodes(a); int lenB = countNodes(b); // pad the shorter list with 0 if (lenA < lenB) { a = padWithZeroInTheBeginning(&a, lenB - lenA); } else { b = padWithZeroInTheBeginning(&b, lenA - lenB); } // add lists partialSum p = {.pSum = (node*)malloc(sizeof(node)), .carry = 0}; p.pSum = NULL; p = addSumForwardHelper(a, b); if (p.carry == 0) { return p.pSum; } else { insertNodeAtBeginning(&(p.pSum), p.carry % 10); return p.pSum; } } partialSum addSumForwardHelper(node* a, node* b) { if (a == NULL && b == NULL) { partialSum temp = {(node*) malloc(sizeof(node)), 0}; temp.pSum = NULL; temp.carry = 0; return temp; } partialSum temp = addSumForwardHelper(a->next, b->next); int val = temp.carry + a->data + b->data; insertNodeAtBeginning(&(temp.pSum), val % 10); temp.carry = val / 10; return temp; }
node* padWithZeroInTheBeginning(node** head, int len) { int counter; for (counter = 0; counter < len; counter++) { insertNodeAtBeginning(head, 0); } printListToConsole(*head); return *head; }
node* createListFromNumberForward(int n) { node* head = (node*) malloc(sizeof(node)); head = NULL; while (n > 0) { insertNodeAtBeginning(&head, n % 10); n /= 10; } return head; }
int insertNodeAtPositionFromBeginning(node** head, int position, int value) { if (position == 0) { insertNodeAtBeginning(head, value); return 1; } else { node* newNode = (node*) malloc(sizeof(node)); newNode->data = value; newNode->next = NULL; if (newNode == NULL) { return 0; } else { node* temp = (*head); int counter = 1; int noNodes = countNodes(*head); if ( noNodes < position) { printf("ADD ERROR: Position to insert is greater than the lenght of the list.\n"); return 0; } else { while (temp->next != NULL && counter != position) { temp = temp->next; counter++; } if (temp->next == NULL) { temp->next = newNode; printf("ADD: Node with value has been added at the end of the list.\n", value); //free(newNode); //free(temp); return 3; } else { newNode->next = temp->next->next; temp->next = newNode; printf("ADD: Adding new node with value %d in position %d in the list.\n", value, position); //free(temp); //free(newNode); return 4; } } } } }
/* * Insert node at index 'i'. * Root node counts as index 0. * Inserting a node at index 1 would mean it pushes the node at index 1 to index 2. */ void LinkedList::insertNodeAt(int i, int x) { if (i == 0) { insertNodeAtBeginning(x); return; } conductor = root; node *temp = new node(); temp->x = x; if (conductor != 0) { while (conductor->next != 0 && i > 1) { i--; //goto next item conductor = conductor->next; } temp->next = conductor->next; conductor->next = temp; } }