python写法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
x = 0
y = 0
carry = 0
curr = ListNode(0)
cur = curr
while(l1 or l2):
x= l1.val if l1 else 0
y= l2.val if l2 else 0
s = x + y + carry
carry = math.floor(s/10)
#哑结点使用
cur.next = ListNode(s%10)
cur = cur.next
#是否到达最右端终点
if(l1!=None):l1 = l1.next
if(l2!=None):l2 = l2.next
if(carry>0):
cur.next= ListNode(1)
return curr.next
java写法
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
相关知识点
-
哑结点:
哑结点其实就是放在第一个存放数据结点之前、头结点之后的结点。
加入哑结点之后就可以使所有数据结点都有前驱结点,这样就会方便执行链表的一些操作
-
链表
链表