【LeetCode刷题记录】2. 两数相加

题目描述:
在这里插入图片描述
单链表定义:

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

打印链表:
正序:

void printListNode(ListNode* ln) {
 ListNode* ln_temp = ln;
 while (ln_temp != NULL) {
  std::cout << ln_temp->val << " ";
  ln_temp = ln_temp->next;
 }
 std::cout << std::endl;
}

反序:

void printListNodeInverse(ListNode* ln) {
 ListNode* ln_temp = ln;
 stack<int> stk;
 while (ln_temp != NULL) {
  stk.push(ln_temp->val);
  ln_temp = ln_temp->next;
 }
 while (!stk.empty()) {
  std::cout << stk.top() << " ";
  stk.pop();
 }
 std::cout << std::endl;
}

题解:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
 ListNode* ph = new ListNode(0);
 ListNode* ln_sum = ph;
 int carry = 0;
 while (l1 != NULL || l2 != NULL) {
  int x = l1 != NULL ? l1->val : 0;
  int y = l2 != NULL ? l2->val : 0;
  int sum = x + y + carry;
  carry = sum >= 10 ? 1 : 0;
  ln_sum->next = new ListNode(sum % 10);
  ln_sum = ln_sum->next;
  if (l1 != NULL)l1 = l1->next;
  if (l2 != NULL)l2 = l2->next;
 }
 if (carry)
  ln_sum->next = new ListNode(1);
 return ph->next;
}
原创文章 23 获赞 0 访问量 992

猜你喜欢

转载自blog.csdn.net/weixin_42192493/article/details/104673048