#include <iostream>
#include <algorithm>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//打印链表
void printLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
return;
}
// 链表的创建
ListNode* createLinkedList(int arr[], int n){
if(n == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1 ; i < n ; i ++){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *result=new ListNode(-1);
ListNode *cur=result;
int c=0;
while(l1 || l2)
{
int a=l1?l1->val:0;
int b=l2?l2->val:0;
int res=(a+b+c)%10;
c=(a+b+c)/10;
cur->next=new ListNode(res);
if (l1)l1=l1->next;
if (l2)l2=l2->next;
cur=cur->next;
}
// 注意这里还有一个大大的陷阱,就是可能最后一位可能有进位
if(c)
{
cur->next=new ListNode(1);
cur=cur->next;
}
return result->next;}
};
int main(){
int arr[] = {1, 2, 7, 9, 9};
int n = sizeof(arr)/sizeof(int);
int arr2[] = {3, 4, 5};
int m = sizeof(arr2)/sizeof(int);
ListNode* head1= createLinkedList(arr, n);
printLinkedList(head1);
ListNode* head2= createLinkedList(arr2, m);
printLinkedList(head2);
ListNode* head3 = Solution().addTwoNumbers(head1,head2);
printLinkedList(head3);
return 0;
}
leetcode 2 add two sum 包含链表创建和打印的程序易于测试
最新推荐文章于 2020-04-12 18:59:01 发布