https://leetcode-cn.com/problems/add-two-numbers/
说实话 我觉得这种题挺恶心的 真不喜欢链表和指针这种东西 思路很简单 具体看代码
方法1:补齐后运算
#include <bits/stdc++.h> using namespace std; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int len1 = 1; int len2 = 1; ListNode *p = l1; ListNode *q = l2; while (p->next != nullptr) { len1++; p = p->next; } while (q->next != nullptr) { len2++; q = q->next; } if (len1 > len2) { //l1长 补l2 for (int i = 1; i <= len1 - len2; i++) { q->next = new ListNode(0); q = q->next; } } else { //l2长 补l1 for (int i = 1; i <= len2 - len1; i++) { p->next = new ListNode(0); p = p->next; } } //指针归位 p = l1; q = l2; bool jud = 0; //记录进位 ListNode *ans = new ListNode(1); ListNode *l3 = ans; int i = 0; while (p != nullptr && q != nullptr) { i = jud + p->val + q->val; l3->next = new ListNode(i % 10); jud = i >= 10 ? 1 : 0; p = p->next; q = q->next; l3 = l3->next; } if (jud) { l3->next = new ListNode(1); l3 = l3->next; } ListNode *preDelete=ans; ans=ans->next; delete preDelete; return ans; } };
方法2:不补齐直接算
#include <bits/stdc++.h> using namespace std; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode* head=new ListNode(-1); ListNode* h=head; int sum=0;//每位相加的答案 int carry=false;//进位 while (l1!=nullptr||l2!=nullptr) { sum=carry;//带上进位标志 //取数 if(l1!=nullptr){ sum+=l1->val; l1=l1->next; } if(l2!=nullptr){ sum+=l2->val; l2=l2->next; } h->next=new ListNode(sum%10); h=h->next; carry=sum>=10?1:0; } if(carry){ h->next=new ListNode(1); } ListNode* preDelete=head; head=head->next; delete preDelete; return head; } };
Comments | NOTHING