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

两个链表生成相加链表

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

双栈的python实现

# 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 , head2 ):
        # write code here
        list1, list2 = [], []
        if not head1:
            return head2
        if not head2:
            return head1
        while head1:
            list1.append(head1.val)
            head1 = head1.next
        while head2:
            list2.append(head2.val)
            head2 = head2.next
        temp = 0
        cur = ListNode(0)
        cur_next = None
        while len(list1)!=0 and len(list2)!=0:
            val1 = list1.pop()
            val2 = list2.pop()
            val_sum = val1 + val2 + temp
            cur = ListNode(val_sum%10)
            cur.next = cur_next
            cur_next = cur
            temp = val_sum//10
        while len(list1)!=0:
            val = list1.pop()
            cur = ListNode((val+temp)%10)
            temp = (val+temp)//10
            cur.next = cur_next
            cur_next = cur
        while len(list2)!=0:
            val = list2.pop()
            cur = ListNode((val+temp)%10)
            temp = (val+temp)//10
            cur.next = cur_next
            cur_next = cur
        if temp==1:
            cur = ListNode(temp)
            cur.next = cur_next
            cur_next = cur
        return cur_next
        
        
        
        
        
        
        
        
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-11 15:08
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 11:33
点赞 评论 收藏
分享
07-05 16:23
门头沟学院 Java
mengnankk:我投了300,约了5 6个面试。感觉项目写的太多了。一个项目就写五六个亮点,不是把整个项目的功能描述下。其他的没啥,简历看起来有点长
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
07-14 13:37
重庆大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务