week2
题目
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
- Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
解析
题目要求用一个链表来表示一个数,其中链表的节点已在题目中给出,其中根据链表顺序组合成的数与其想表示的数的每一位刚好是相反的。解题思路大致为将两个链表中表示相同位的两个数相加,结果作为结果链表中相应位置的数,期间要注意两个数相加大于等于10时要进位。
在本题具体解题过程中我使用了两个队列来依次记录两个加数的每一位,方便后面进行相加。
代码
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
/*将两个加数的每一位分别记录在两个队列中*/
queue<int> Q1, Q2;
ListNode *temp1 = l1, *temp2 = l2;
while (temp1 != NULL) {
Q1.push(temp1->val);
temp1 = temp1->next;
}
while (temp2 != NULL) {
Q2.push(temp2->val);
temp2 = temp2->next;
}
/*记录当前操作的节点是否为链表的头结点*/
bool first = true;
ListNode *result = NULL;
ListNode *temp = NULL;
/*第一个加数长度大于等于第二个加数长度的情况*/
if (Q1.size() >= Q2.size()) {
int carry = 0; /*记录进位*/
/*计算两个加数的相同位*/
while (Q2.size() > 0) {
int sum = Q1.front() + Q2.front() + carry;
if (sum >= 10) {
carry = 1;
sum -= 10;
} else {
carry = 0;
}
if (first) {
temp = new ListNode(sum);
result = temp;
first = false;
}
else {
temp->next = new ListNode(sum);
temp = temp->next;
}
Q1.pop();
Q2.pop();
}
/*计算位数更多的加数多出来的高位*/
while (Q1.size() > 0) {
int sum = Q1.front() + carry;
if (sum >= 10) {
carry = 1;
sum -= 10;
} else {
carry = 0;
}
temp->next = new ListNode(sum);
temp = temp->next;
Q1.pop();
}
/*如果最高位还有进位则结果链表新增一位*/
if (carry == 1) {
temp->next = new ListNode(carry);
temp = temp->next;
}
}
/*第二个加数长度大于第一个加数的情况*/
else {
int carry = 0;
while (Q1.size() > 0) {
int sum = Q1.front() + Q2.front() + carry;
if (sum >= 10) {
carry = 1;
sum -= 10;
}
else {
carry = 0;
}
if (first) {
temp = new ListNode(sum);
result = temp;
first = false;
}
else {
temp->next = new ListNode(sum);
temp = temp->next;
}
Q1.pop();
Q2.pop();
}
while (Q2.size() > 0) {
int sum = Q2.front() + carry;
if (sum >= 10) {
carry = 1;
sum -= 10;
}
else {
carry = 0;
}
temp->next = new ListNode(sum);
temp = temp->next;
Q2.pop();
}
if (carry == 1) {
temp->next = new ListNode(carry);
temp = temp->next;
}
}
return result;
}
};