Try   HackMD

2. Add Two Numbers

https://leetcode.com/problems/add-two-numbers/
Medium

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Solution

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* Addnode(int val){ struct ListNode * new = malloc(sizeof(struct ListNode)); new -> val = val; new -> next = NULL; return new; } struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ struct ListNode * head = NULL; struct ListNode * current = NULL; struct ListNode * rear = NULL; int c = 0; int result = 0; while(l1!=NULL||l2!=NULL){ result = c +(l1?l1->val:0)+(l2?l2->val:0); c = (result>9)?1:0; result = result%10; current = Addnode(result); if(!head) head = current; else rear ->next = current; rear = current; if(l1) l1=l1->next; if(l2) l2=l2->next; } if(c == 1) rear->next = Addnode(1); return head; }

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →