GeeksforGeeks » Interview Questions
Amazon Interview Question for Software Engineer/Developer about Linked Lists
(4 posts)-
Integer has been represented in linked list. Eg. 7541 has been represented as 7->5->4->1 with 4 nodes each having a digit. Given 2 such linked lists, you need to compute the sum of them
-
We can do this as follows:
1. traverse first list
2. while traversing it self calculate the number value by num1 = (num1*10) + value at node of list1.
3. similarly num2 = (num2*10) + value at node of list2
4. Sum = num1 + num2 -
//WAP to SumTwo Number Which are represented by node in linked list #include<stdio.h> #include<malloc.h> #include<stdlib.h> /* Link list node */ struct node { int data; struct node* next; }; /* Function to reverse the linked list */ static void reverse(struct node** head_ref) { struct node* prev = NULL; struct node* current = *head_ref; struct node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; } /* Function to push a node */ void push(struct node** head_ref, int new_data) { /* allocate node */ struct node* new_node = (struct node*) malloc(sizeof(struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } struct node* addition (struct node* temp1, struct node* temp2) { struct node* prev = NULL; int carry = 0,a,b,result; while (temp1 || temp2) //while both lists exist { if(temp1) a=temp1->data; else a=0; if(temp2) b=temp2->data; else b=0; result = carry; if(temp1) result+=temp1->data; if(temp2) result+=temp2->data; carry=result/10; struct node * newnode = (struct node*) malloc (sizeof(struct node)); newnode->data=(result)%10; newnode->next = prev; prev=newnode; if(temp1) temp1=temp1->next; if(temp2) temp2=temp2->next; } return prev; } void printList(struct node *node) { while(node != NULL) { printf("%d ", node->data); node = node->next; } } /* Drier program to test above function*/ int main(void) { /* Start with the empty list */ struct node* head = NULL; struct node* head1 = NULL; struct node* head2 = NULL; /* Created Linked list is 1->2->3->4->5->6->7->8 */ push(&head1, 4); push(&head1, 3); push(&head1, 2); push(&head1, 1); printf("list 1 is \t"); printList(head1); printf("\n"); reverse(&head1); push(&head2, 6); push(&head2, 5); push(&head2, 4); printf("list 2 is \t"); printList(head2); printf("\n"); reverse(&head2); head=addition(head1,head2); printf("resultant list is \t"); printList(head); printf("\n"); return(0); } -
awesome work...thankQ soooooo much
Reply
You must log in to post.