首页 > 其他 > 详细

LeetCode(Add Two Numbers)

时间:2019-01-13 23:07:07      阅读:184      评论:0      收藏:0      [点我收藏+]

一、题目要求

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语言

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
 9     struct ListNode* p1 = l1, *p2 = l2;
10     struct ListNode* new_node = 0;
11     struct ListNode* ret_node = 0;
12     struct ListNode* temp_node = 0;
13     int sum = 0;
14 
15     while(p1 != NULL || p2 != NULL || sum != 0) {
16         int temp = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + sum;
17         int val = temp % 10;
18         sum = temp / 10;
19 
20         new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
21         new_node->val = val;
22         new_node->next = 0;
23 
24         if (0 == temp_node) {
25             temp_node = new_node;
26             ret_node = temp_node;
27         } else {
28             temp_node->next = new_node;
29             temp_node = new_node;
30         }
31 
32         p1 = p1 ? p1->next : p1;
33         p2 = p2 ? p2->next : p2;
34     }
35     return ret_node;
36 }

分析:根据题目的要求,将链表中对应元素相加,最后,倒序输出为一个链表结构。

需要注意:

  • 链表长度不相同情况,比如一个[1,2,3],例外一个是[1,2,3,4,5,6]情况时,实现方法:
    p1 ? p1->val : 0
  • 考虑进位情况,实现方法:
    int temp = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + sum;
    int val = temp % 10;
    sum = temp / 10;
  • 考虑输出链表顺序问题,实现方法:
    if (0 == temp_node) {
        temp_node = new_node;
        ret_node = temp_node;
    } else {
        temp_node->next = new_node;
        temp_node = new_node;
    }

     

 

运行结果:

技术分享图片

 

LeetCode(Add Two Numbers)

原文:https://www.cnblogs.com/zou107/p/10261312.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!