当前位置: 首页 > 文档资料 > LeetCode 题解 >

Linked List - Add Two Numbers

优质
小牛编辑
131浏览
2023-12-01

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

两个链表相加的问题,需要处理好进位就成了,比较简单,直接上代码:

  1. class Solution {
  2. public:
  3. ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  4. ListNode dummy(0);
  5. ListNode* p = &dummy;
  6. int cn = 0;
  7. while(l1 || l2) {
  8. int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
  9. cn = val / 10;
  10. val = val % 10;
  11. p->next = new ListNode(val);
  12. p = p->next;
  13. if(l1) {
  14. l1 = l1->next;
  15. }
  16. if(l2) {
  17. l2 = l2->next;
  18. }
  19. }
  20. if(cn != 0) {
  21. p->next = new ListNode(cn);
  22. p = p->next;
  23. }
  24. return dummy.next;
  25. }
  26. };