PREP57 Editorial

Explanation

  • We create a new node for the sum linked list: curr and two pointers: p and q for traversing the two linked list numbers which are initialized with the head of l1 and l2.
  • We initialize a carry variable as 0.
  • We start a while loop till p and q are not NULL.
  • we save the data of p and q in variables x and y if p and q are not null. Otherwise, 0 is stored.
  • Sum is calculated by adding carry, x and y.
  • Carry is updated with the value of Sum/10 which gives digits after removing the oneth position digit.
  • A new node is created for the next digit in sum and is stored in the next of curr.
  • curr is updated to next of curr.
  • p and q are updated to their next value if they are not NULL.
  • If carry is not zero, it is appended onto the sum linked list.
  • The start of the sum linked list is returned as the head.