leetcode 2 add two sum 包含链表创建和打印的程序易于测试

在这里插入图片描述

#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值