Leetcode#2 Add Two Numbers

原题地址

 

基本链表操作

 

代码:

 1 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {

 2         ListNode *h = NULL;

 3         ListNode *t = NULL;

 4         int carry = 0;

 5         

 6         while (l1 && l2) {

 7             ListNode *node = new ListNode((l1->val + l2->val + carry) % 10);

 8             carry = (l1->val + l2->val + carry) / 10;

 9             if (!h)

10                 h = t = node;

11             else {

12                 t->next = node;

13                 t = t->next;

14             }

15             l1 = l1->next;

16             l2 = l2->next;

17         }

18         while (l1) {

19             ListNode *node = new ListNode((l1->val + carry) % 10);

20             carry = (l1->val + carry) / 10;

21             if (!h)

22                 h = t = node;

23             else {

24                 t->next = node;

25                 t = t->next;

26             }

27             l1 = l1->next;

28         }

29         while (l2) {

30             ListNode *node = new ListNode((l2->val + carry) % 10);

31             carry = (l2->val + carry) / 10;

32             if (!h)

33                 h = t = node;

34             else {

35                 t->next = node;

36                 t = t->next;

37             }

38             l2 = l2->next;

39         }

40         if (carry > 0)

41             t->next = new ListNode(carry);

42             

43         return h;

44 }

 

你可能感兴趣的:(LeetCode)