Skip to content

Instantly share code, notes, and snippets.

@jitsceait
Last active August 29, 2015 14:00
Show Gist options
  • Save jitsceait/a014f9709937f96d2c5e to your computer and use it in GitHub Desktop.
Save jitsceait/a014f9709937f96d2c5e to your computer and use it in GitHub Desktop.
This program adds numbers represented by two linked lists
#include<stdlib.h>
#include<stdio.h>
typedef struct node{
int data;
struct node *next;
} Node;
/* This function is actually helper function which does all house keeping like
calculating lengths of lists,calling recursive implementation, creating extra
node for carry in MSD,and adding any remaining nodes left in longer list. */
/* result is pointer to pointer to the head of resulting node */
void add_list2(Node *L1, Node *L2, int *carry, Node **result){
int len1 = 0;
int len2 = 0;
int diff =0;
Node * current = L1;
while(current){
current = current->next;
len1++;
}
current = L2;
while(current){
current = current->next;
len2++;
}
if(len1 < len2){
current = L1;
L1 = L2;
L2 = current;
}
diff = abs(len1-len2);
current = L1;
while(diff--)
current = current->next;
/* Call the recursive implementation */
add_list(current, L2, carry, result);
diff = abs(len1-len2);
/* Add remaining nodes in longer list */
add_remaining(L1, carry, result, diff);
if(*carry){
Node * temp = (Node *)malloc(sizeof(Node));
temp->next = (*result);
*result = temp;
}
return;
}
void add_list(Node *L1, Node *L2, int *carry, Node **result){
int sum;
if(!L1)
return;
add_list(L1->next, L2->next, carry, result);
/*We have reached the last node of both lists, add them */
Node * temp = (Node *)malloc(sizeof(Node));
sum = L1->data + L2->data + (*carry);
// Store carry
*carry = sum/10;
sum = sum%10;
temp->data = sum;
/* Link pointers in resulting linked list */
temp->next = (*result);
/* change the resulting pointer. */
*result = temp;
return;
}
void add_remaining(Node * L1, int *carry, Node **result, int diff){
int sum =0;
if(!L1 || diff == 0)
return;
add_remaining(L1->next, carry, result, diff-1);
Node * temp = (Node *)malloc(sizeof(Node));
sum = L1->data + (*carry);
*carry = sum/10;
sum = sum%10;
temp->data = sum;
temp->next = (*result);
*result = temp;
return;
}
/* Addition of a node to linked list */
void push(Node **head, int value){
if(*head == NULL){
(*head) = (Node *)malloc(sizeof(Node));
(*head)->data = value;
(*head)->next = NULL;
}
else{
Node * temp = (Node *)malloc(sizeof(Node));
if(temp){
temp->data = value;
temp->next = (*head);
*head = temp;
}
}
}
/* Driver program to run above code */
int main(){
Node * L1 = NULL;
Node * L2 = NULL;
Node * result = NULL;
int carry = 0 ;
/* creating list 1 */
push(&L1,3);
push(&L1,4);
push(&L1,6);
push(&L1,7);
/* creating list 2 */
push(&L2,8);
push(&L2,9);
push(&L2,7);
add_list2(L1,L2, &carry, &result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment