//与倒序不同,如果程序一开始没有reverse l1,不能直接返回l1,因为其依然指向原头结点,即现尾节点
class Solution {
public:
ListNode* reverseListNode(ListNode* head) {
ListNode* preNode = NULL;
ListNode* curNode = head;
while (curNode != NULL) {
ListNode* next = curNode->next;
curNode->next = preNode;
preNode = curNode;
curNode = next;
}
return preNode;
}
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
l1 = reverseListNode(l1);
l2 = reverseListNode(l2);
int k = 0, sum;
ListNode* curNode1 = l1;
ListNode* curNode2 = l2;
ListNode* temp = NULL;
while (curNode1 != NULL && curNode2 != NULL) {
sum = curNode1->val + curNode2->val + k;
curNode1->val = sum % 10;
k = sum / 10;
temp = curNode1;
curNode1 = curNode1->next;
curNode2 = curNode2->next;
}
if (curNode2 != NULL) {
//deleteLinkedList(temp->next);
curNode1 = curNode2;
temp->next = curNode1;
}
while (curNode1 != NULL && k != 0) {
sum = curNode1->val + k;
curNode1->val = sum % 10;
k = sum / 10;
temp = curNode1;
curNode1 = curNode1->next;
}
if (k == 1) temp->next = new ListNode(1);
return reverseListNode(l1);
}
};
int main()
{
Solution sol;
vector<int> input1 = {7,2,4,3}, input2 = {5,6,4};
ListNode *l1 = createListNode(input1);
ListNode *l2 = createListNode(input2);
//printLinkedList(sol.reverseListNode(l1));
//printLinkedList(sol.reverseListNode(l2));
printLinkedList(sol.addTwoNumbers(l1, l2));
//deleteLinkedList(l1);
//deleteLinkedList(l2);
return 0;
}