Contents

最近从知乎上知道了leetcode,十分高兴的一点是竟然可以使用python语言进行提交,于是果断在leetcode上开始刷题,熟悉了python,又提高了自己编程的能力。
今天要做的是Add Two Numbers,这道题是很简单的链表操作,直接上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @return a ListNode
def addTwoNumbers(self, l1, l2):
head = tail = ListNode(0)
flag = 0
while l1 or l2 or flag:
node = ListNode(flag)
if l1:
node.val = node.val + l1.val
l1 = l1.next
if l2:
node.val = node.val + l2.val
l2 = l2.next
flag = node.val / 10
node.val = node.val % 10
tail.next = node
tail = tail.next
tail.next = None
return head.next

坚持就是胜利

Contents