两数相加
解上述题,采用同样的思路。
go实现对比c++实现,结果如下图所示:
image.png
C++实现
/**
* 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) {
//注意:1、链表是逆序的,返回链表也是逆序
// 按输入两链表顺序加,有进位的话,就需要在后一个节点加上。
// 2、最后,需要保存链表头,同时还需要一个处理链表。
ListNode *head = new ListNode(-1);
ListNode *node = head;
int carry = 0;
while(l1 || l2) {
int val1 = 0, val2 = 0;
if (l1 != nullptr) {
val1 = l1->val;
l1 = l1->next;
}
if (l2 != nullptr) {
val2 = l2->val;
l2 = l2->next;
}
int sum = val1 + val2 + carry;
carry = sum / 10;
node->next = new ListNode(sum % 10);
node = node->next;
}
if(carry != 0) {
node->next = new ListNode(carry);
}
return head->next;
}
};
GO实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
ans := new(ListNode)
curr := ans
carry := 0
for (l1 != nil || l2 != nil) {
val1,val2 := 0,0
if l1 != nil {
val1 = l1.Val
l1 = l1.Next
}
if l2 != nil {
val2 = l2.Val
l2 = l2.Next
}
sum := val1 + val2 + carry
carry = sum / 10
temp := new(ListNode)
temp.Val = sum % 10
temp.Next = nil
curr.Next = temp
curr = curr.Next
}
if carry != 0 {
temp := new(ListNode)
temp.Val = carry
temp.Next = nil
curr.Next = temp
}
return ans.Next
}
网友评论