题目理解:这题目的意思是传入这个方法里的是,两个逆序的链表,而题目给出的示例,只是输入的值,则运算的方法里返回值也是逆序的就好。
Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} };ListNode() : val(0), next(nullptr) {}
意思
ListNode(){
val =0;
next=nullptr;
}
lass Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *p = l1; ListNode *q = l2; int add_set = 0; while (l1 && l2) { int sum = l1->val + l2->val + add_set; if (sum >= 10) { add_set = 1; l1->val = sum % 10; } else { add_set = 0; l1->val = sum; } if (l1->next && l2->next) { l1 = l1->next; l2 = l2->next; } else { break; } } if (!l1->next) { l1->next = l2->next;//由于l1为空,所以退出了上面的循环,将l2->next接到l1后面 } while (add_set) { if (!l1->next) {//l2后面也没值了 l1->next = new ListNode(1);//由于进位还为1,所以初始化时,将该节点加上进位的值 add_set = 0; } else { l1 = l1->next;//l2->next不为空 int sum = l1->val + add_set; if (sum >= 10) { add_set = 1; l1->val = sum % 10; } else { add_set = 0; l1->val = sum; } } } return p;//返回的是默认的逆序 } };
标签:set,ListNode,val,相加,next,l2,l1 From: https://www.cnblogs.com/wonder-question/p/17813532.html