题目描述(两数相加)
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。(你可以假设除了数字 0 之外,这两个数都不会以 0 开头。)
答:向后移动指针加到t上, res->next = new ListNode(t%10);
,如果有进位t = t/10;
暴力解法
- 由于是倒叙排列,只需要将链表的值读取出来,然后加起来放入结果链表中即可。(对于加法的进位问题,只需要一个整数记录是否进位即可)
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) {
ListNode *res = new ListNode(0);
ListNode* pre = res;//记录一下结果的头指针
int t=0;// 维护进位值
while(l1 !=NULL || l2!=NULL|| t!=0 ){
if(l1 !=NULL)
{t= t+ (*l1).val;l1 = (*l1).next;}
if(l2 !=NULL)
{t= t+ (*l2).val;l2 = l2->next;}
res->next = new ListNode(t%10);
t = t/10;
res = res->next;
}
return pre->next;
}
};
java(感觉和c++差不多,只是没了地址操作)
/**
* 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 res = new ListNode(); // 结果链表
ListNode pre = res;
int t=0;// 维护进位值
while(l1 !=null || l2!=null|| t!=0 ){
if(l1 !=null)
{t= t+ (l1).val;l1 = (l1).next;}
if(l2 !=null)
{t= t+ (l2).val;l2 = l2.next;}
res.next = new ListNode(t%10);
t = t/10;
res = res.next;
}
return pre.next;// 注意 不使用结果为 [0,7,0,8],在c++中pre是一个地址,而java中直接就是一个ListNode
}
}
- 这样写还是挺快的
python 链表
- 去掉地址符号 * ,-> (换为。)
- 去掉 ;
- 去掉{} 改为缩进和 :
- 去掉 类型声明
- 去掉new关键字
- NULL 改为 None
- 最后加上某些数值强制为int
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
res = ListNode();
pre = res
t=int(0)
while(l1 or l2 or t!=0):
if(l1 !=None):
t= t+ (l1).val
l1 = (l1).next
if(l2 !=None):
t= t+ (l2).val
l2 = l2.next
res.next = ListNode(int(t%10))
t = int(t/10)
res = res.next
return pre.next
其他解法(略)
总结
1.c++链表c++链表
2. c++ 中 p->b等同于(*p).b
运算符"*“地址在 优先级3 ,取成员”."为优先级2需要以下写法
t= (*l1).val + (*l2).val;// 写法 t= *l1.val + *l2.val;会报错
3.candidate constructor the implicit not struct ListNode deference
ListNode *dummyHead = new ListNode();% 需要改为“地址类型” 写法ListNode dummyHead = new ListNode();会报错