题目:2. 两数相加
思路:链表,时间复杂度0(n)。
C++版本:
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode * head=new ListNode(0);
ListNode * p=head;
int c=0;
while(l1!=nullptr || l2!=nullptr){
if(l1){
c+=l1->val;
l1=l1->next;
}
if(l2){
c+=l2->val;
l2=l2->next;
}
ListNode *tmp=new ListNode(c%10);
p->next=tmp;
p=tmp;
c/=10;
}
while(c>0){
ListNode *tmp=new ListNode(c%10);
p->next=tmp;
p=tmp;
c/=10;
}
if(head->next==nullptr) return head;
return head->next;
}
};
JAVA版本:
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=new ListNode(0);
ListNode p=head;
int c=0;
while(l1!=null || l2!=null){
if(l1!=null){
c+=l1.val;
l1=l1.next;
}
if(l2!=null){
c+=l2.val;
l2=l2.next;
}
ListNode tmp=new ListNode(c%10);
p.next=tmp;
p=tmp;
c/=10;
}
while(c>0){
ListNode tmp=new ListNode(c%10);
p.next=tmp;
p=tmp;
c/=10;
}
if(head.next==null) return head;
return head.next;
}
}
GO版本:
go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
head:=&ListNode{0,nil}
p:=head
c:=0
for l1!=nil || l2!=nil {
if l1!=nil {
c+=l1.Val
l1=l1.Next
}
if l2!=nil {
c+=l2.Val
l2=l2.Next
}
tmp:=&ListNode{c%10,nil}
p.Next=tmp
p=tmp
c/=10
}
for c>0 {
tmp:=&ListNode{c%10,nil}
p.Next=tmp
p=tmp
c/=10
}
if head.Next==nil {
return head
}
return head.Next
}