两数相加
算法思路:从低位开始相加,然后把所得个位数保存在新的链表中,并用count来存储进位。
结构体参数列表初始化
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//使用参数列表初始化结构体
ListNode* p = new ListNode(-1);
//一般声明结构体
ListNode p = {1,new ListNode}
链表的声明
struct ListNode{
int m_key;
ListNode* next;
};
void createList(ListNode* pHead){
ListNode* p = pHead;
for (int i = 1; i < 10; ++i) {
ListNode* pNewNode = new ListNode;
pNewNode->m_key = i; // 将新节点的值赋值为i
pNewNode->next = NULL;
p->next = pNewNode; // 上一个节点指向这个新建立的节点
p = pNewNode; // p节点指向这个新的节点
}
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int sum = 0;
int count = 0;
ListNode* l3=new ListNode(-1);
ListNode* w = l3;
while(l1!=NULL&&l2!=NULL){
sum = l1->val+l2->val+count;
w->next = new ListNode(sum%10);
count = sum/10;
l1 = l1->next;
l2 = l2->next;
w = w->next;
}
while(l1!=NULL){
sum = l1->val+count;
w->next = new ListNode(sum%10);
count = sum/10;
l1 = l1->next;
w = w->next;
}
while(l2!=NULL){
sum = l2->val+count;
w->next = new ListNode(sum%10);
count = sum/10;
l2 = l2->next;
w = w->next;
}
if (count == 1) w->next = new ListNode(1);
return l3->next;
}
};