欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add Two Numbers(2)

程序员文章站 2024-03-17 22:00:04
...

2— Add Two Numbers

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 contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

C代码:

// struct ListNode {
//   int val;
//   struct ListNode *next;
// };

//在尾部插入一个Node
int appendList(struct ListNode *l,int data){
  struct ListNode *ptr = l;
  while(ptr && ptr->next != NULL){
    ptr = ptr ->next;
  }
  struct ListNode *tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
  if(!tmp){
    return 0;
  }
  tmp -> val = data;
  tmp -> next = NULL;
  ptr -> next = tmp;
  return 1;

}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *result = (struct ListNode*)malloc(sizeof(struct ListNode));
    result -> next = NULL;
    int flag = 0;     // 进位标志
    struct ListNode *ptr1 = l1 ,*ptr2 = l2;
    int data1,data2,data3,sum;
    while(ptr1||ptr2){       //将[9,9,9]+[1]->[9,9,9]+[1,0,0]
      data1 = (ptr1 == NULL)? 0:ptr1->val;
      data2 = (ptr2 == NULL)? 0:ptr2->val;
      // printf("d1= %d d2=%d\n",data1,data2 );
      sum = (flag == 1)? data1 + data2 + 1 : data1 + data2;

      data3 = sum % 10;
      flag = sum / 10;
      // printf("d1= %d d2=%d d3=%d\n",data1,data2,data3 );
      appendList(result,data3);
      ptr1 = ptr1?ptr1->next:ptr1;
      ptr2 = ptr2?ptr2->next:ptr2;
    }

    if(flag == 1){       // 最后一个进位,如[9,9]+[1] = [0,0,1]
      appendList(result,1);
    }

    return result->next;

}

C++代码:

// struct ListNode {
//   int val;
//   ListNode *next;
//   ListNode(int x) : val(x), next(NULL) {}
// };

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      int flag = 0;
      ListNode preHead(0),*p = &preHead;
      while(l1 || l2){
        int sum = (l1?l1->val:0) + (l2?l2->val:0) + flag;
        flag = sum / 10;
        p-> next = new ListNode(sum % 10);
        p = p->next;
        l1 = l1?l1->next : l1;
        l2 = l2?l2->next : l2;
      }
      if(flag == 1){
        p->next = new ListNode(1);
      }
      return preHead.next;
    }
};

Complexity Analysis:

Time complexity : O(n2n^{2}).
Space complexity : O(n).

思路:

  • 将999+1 转化成999+001, 即[9,9,9]+[1]->[9,9,9]+[1,0,0], 循环次数为最长链表长度.

上一篇: Swift中extension的思考

下一篇: