Loading

2-两数相加

1、注意链表结点的申请格式和头指针的运用

2、注意每位相加的时候考虑进位的问题

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
12         ListNode *head=new ListNode(0);//头节点,方便操作
13         ListNode *current;
14         current=head;
15         int num;
16         int jinwei=0;//进位
17         int shuzhi=0;//存进节点的数值
18         while(l1!=NULL || l2!=NULL)
19         {
20             num=0;
21             if(l1!=NULL)
22             {
23                 num+=l1->val;
24                 l1=l1->next;
25             }
26             if(l2!=NULL)
27             {
28                 num+=l2->val;
29                 l2=l2->next;
30             }
31             num+=jinwei;
32             jinwei=num/10;
33             shuzhi=num%10;
34             /*新的节点*/
35             ListNode *newNode=new ListNode(shuzhi);
36             current->next=newNode;
37             current=current->next;
38         }
39 
40          /*进位不为0,仍要创建新的节点*/
41         if(jinwei!=0)
42         {
43             ListNode *newNode=new ListNode(1);
44             current->next=newNode;
45             current=current->next;
46         }
47         return head->next;
48     }
49 };
50 
51 作者:wakanda_forever
52 链接:https://leetcode-cn.com/problems/add-two-numbers/solution/liang-shu-xiang-jia-cde-lian-biao-jie-fa-by-wakand/
53 来源:力扣(LeetCode)
54 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
View Code

 

链表相关知识点:

https://blog.csdn.net/u011391629/article/details/52137276/

posted @ 2020-03-09 09:26  是凉城吖  阅读(133)  评论(0)    收藏  举报