您将获得两个链接列表,表示两个非负数。 数字以相反的顺序存储,并且它们的每个节点包含单个数字。 添加两个数字并将其作为链接列表返回。 输入:(2→4→3)+(5→6→4) 输出:7 - > 0 - > 8
/** * 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) { ListNode *Nhead = new ListNode(0); ListNode *head = Nhead; int carry = 0; int sum = 0; while (l1 || l2 || carry){//三种情况,链表加完之后看是否还有进位 int sum = 0; if (l1){ sum += l1->val; l1 = l1->next; } if (l2){ sum += l2->val; l2 = l2->next; } sum = sum + carry;//各个位置的和 head->next = new ListNode(sum%10);//直接构造链表值 head = head->next; carry = sum/10;//进位情况 } return Nhead->next; } };
原文:http://www.cnblogs.com/Kobe10/p/6366231.html