文章目录
2. 两数相加
思路–模拟加法运算
- 其实这道题思路很简单:只要我们模拟加法运算即可;
- 遍历两个链表,拿结点相加,要控制进位值;
需要注意的是:要处理最后一个结点的进位值;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
//虚拟头结点,方便尾插结果结点
ListNode* dummyHead =new ListNode(0);
ListNode* tail = dummyHead;
int sum = 0; //总和
int carry = 0; //进位
while(l1!=NULL || l2!=NULL)
{
//计算两个链表的和
int n1 = 0; //假如cur1为空,那么该结点值为0,要控制
if(l1!=NULL)
{
n1 = l1->val;
}
int n2 = 0;//假如cur2为空,那么该值为0,要控制
if(l2!=NULL)
{
n2 = l2->val;
}
sum = n1 +n2 +carry;
carry = sum / 10; //处理进位值
//给新结点插入sum % 10值,即是各位的值
ListNode* newNode =new ListNode(sum % 10);
//尾插
tail->next = newNode;
tail = tail->next; //处理tail指针
//迭代 l1 和 l2 结点往下走
if(cur1 != NULL)
cur1 = cur1->next;
if(cur2 !=NULL)
cur2 = cur2->next;
}
//退出循环,要判断最后一个结点是否有进位!
if(carry >0)
{
ListNode* newNode =new ListNode(carry);
//尾插
tail->next = newNode;
tail = tail->next; //处理tail指针
}
tail->next = NULL;
return dummyHead->next;
}