题解 | #链表相加(二)#

链表相加(二)

http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        cur1 = head1
        cur2 = head2
        pre1 = None
        pre2 = None
        pre = cur = ListNode(0)
        while cur1: #翻转链表1,pre1为翻转后的头指针
            tmp = cur1.next
            cur1.next = pre1
            pre1 = cur1 
            cur1 = tmp
        while cur2:#翻转链表2,pre2为翻转后的头指针
            tmp = cur2.next
            cur2.next = pre2
            pre2 = cur2 
            cur2 = tmp
        cur1 = pre1 #把头指针赋值给cur1
        cur2 = pre2#把头指针赋值给cur2
        c = 0#进位标志
        while cur1 and cur2:
            cur.next = ListNode(0)
            cur.next.val = (cur1.val + cur2.val + c)%10
            cur = cur.next
            c = (cur1.val + cur2.val + c)//10
            cur1 = cur1.next
            cur2 = cur2.next
        while cur1:
            cur.next = ListNode(0)
            cur.next.val = (cur1.val + c)%10
            cur = cur.next
            c = (cur1.val + c)//10
            cur1 = cur1.next
        while cur2:
            cur.next = ListNode(0)
            cur.next.val = (cur2.val + c)%10
            cur = cur.next
            c = (cur2.val + c)//10
            cur2 = cur2.next
        if c == 1 :
            cur.next = ListNode(1) 
        post = None
        cur = pre.next
        while cur:
            tmp = cur.next
            cur.next = post 
            post = cur 
            cur = tmp
        return post
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:28
点赞 评论 收藏
分享
11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务