Note that there are some explanatory texts on larger screens.

plurals
  1. POadding two linked lists efficiently in C
    text
    copied!<p>I have two linked lists representing the digits of decimal numbers in order from most- to least-significant. for eg <code>4-&gt;7-&gt;9-&gt;6</code> and <code>5-&gt;7</code> The answer should be <code>4-&gt;8-&gt;5-&gt;3</code> without reversing the lists because reversing the lists would result in decrease of efficiency.</p> <p>I am thinking of solving the problem using stack.I will traverse both the lists and push the data elements into two separate stacks.One for each linked list.Then I pop both the stacks together and add both the elements and if the result is a two digit no I 10 modulo it and store the carry in a temp variable.The remainder is stored in the node and the carry is added to the next sum and so on. if the two stacks are s1 and s2 and the result linked list is res.</p> <pre><code>temp = 0; res = (node*)(malloc(sizeof(node*)); while(s1-&gt;top!=-1 || s2-&gt;top!=-1) { temp = 0; sum = pop(s1) + pop(s2); n1 = (node*)(malloc(sizeof(node*)); temp = sum/10; sum = sum%10; sum = sum+temp; n1-&gt;data = sum; n1-&gt;next = res; res = n1; free n1; //temp=0; } if((s1-&gt;top==-1)&amp;&amp;(s2-&gt;top==-1)) { return res; } else if(s1-&gt;top==-1) { while(s2-&gt;top!=-1) { temp = 0; sum = pop(s2); sum = sum + temp; temp = sum/10; sum = sum%10; n1 = (node*)(malloc(sizeof(node*)); n1-&gt;data = sum; n1-&gt;next = res; res = n1; free n1; } } else { while(s2-&gt;top!=-1) { temp = 0; sum = pop(s2); sum = sum+temp; temp = sum/10; sum = sum%10; n1=(node*)(malloc(sizeof(node*)); n1-&gt;data = sum; n1-&gt;next = res; res = n1; free n1; } } return res; </code></pre> <p>I have come across this problem many times in interview questions but this is the best solution that I could think of. If anyone can come with something more efficient in c i will be very glad.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload