题解 | #两个链表生成相加链表#

两个链表生成相加链表

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
        head1r = self.reverse(head1)
        head2r = self.reverse(head2)
        head = ListNode(0)
        curr = head
        jw = 0
        while head1r or head2r or jw > 0:
            if head1r and head2r:
                s = head1r.val + head2r.val + jw
                head1r = head1r.next
                head2r = head2r.next
            elif head1r:
                if jw > 0:
                    s = head1r.val + jw
                    head1r = head1r.next
                else:
                    curr.next = head1r
                    break
            elif head2r:
                if jw > 0:
                    s = head2r.val + jw
                    head2r = head2r.next
                else:
                    curr.next = head2r
                    break
            else:
                s = jw
            bw = s % 10      # 本位
            jw = int(s/10)   # 进位
            curr.next = ListNode(bw)
            curr = curr.next
        return self.reverse(head.next)

    @staticmethod
    def reverse(head):    # 反转链表
        new_head = None
        while head:
            next_head = head.next
            head.next = new_head
            new_head = head
            head = next_head
        return new_head

        
全部评论

相关推荐

牛客963010790号:为什么还要收藏
点赞 评论 收藏
分享
投递小天才等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务