Add Two Numbers
2015-05-08 11:18
120 查看
1、新建一个链表,并赋值
题目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、用链表做加法,每个节点代表一位数;
2、记录进位;
3、新建链表,显示相加的结果,返回;
代码:
ListNode *result=new ListNode(c%10); if(head==NULL) head=result; else prev->next=result; prev=result; return head;
题目:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、用链表做加法,每个节点代表一位数;
2、记录进位;
3、新建链表,显示相加的结果,返回;
代码:
/** * 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 *prev=NULL; ListNode *head=NULL; int c=0; while(l1!=NULL || l2!=NULL || c!=0) { if(l1!=NULL) { c+=l1->val; l1=l1->next; } if(l2!=NULL) { c+=l2->val; l2=l2->next; } ListNode *result=new ListNode(c%10); if(head==NULL) head=result; else prev->next=result; prev=result; c=c/10; } return head; } };
相关文章推荐
- Add Two Numbers
- 2. Add Two Numbers
- LeetCode Add Two Numbers 空头节点
- LeetCode | Add Two Numbers
- 2. Add Two Numbers
- LeetCode-Add Two Numbers_002
- LeetCode--------AddTwoNumbers
- [刷题]Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode Add Two Numbers
- leetcode2 Add Two Numbers(JavaScript)
- 2. Add Two Numbers
- leetcode第四题--Add Two Numbers
- leetCode:2. Add Two Numbers
- leetcode 59: Add Two Numbers
- Given an array of integers, return indices of the two numbers such that they add up to a specific ta
- LeeCode(No2 - Add Two Numbers)
- Add Two Numbers
- 【LeetCode】【Python】【C++】2. Add Two Numbers代码实现
- LeetCode 2. Add Two Numbers