lintcode练习 - 904. 加一链表

904. 加一链表

给定一个非负整数,这个整数表示为一个非空的单链表,每个节点表示这个整数的一位。返回这个整数加一。

除了0本身,所有数字在最高位前都没有0。

列表的头节点存的是这个整数的最高位。

样例

给出链表1 -> 2 -> 3 -> null,返回 1 -> 2 -> 4 -> null

实现思路:

用数组和用链表两种方法

当使用链表时,先将链表翻转过来,然后加一以后再翻转

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


#用数组操作
class Solution:
    """
    @param head: the first Node
    @return: the answer after plus one
    """
    def plusOne(self, head):
        # Write your code here
        #用数组操作
        count = 0
        cur = head
        while cur:
            count = count * 10 + cur.val
            cur = cur.next
        
        count += 1
        dummy = ListNode(0)
        pre = dummy
        while count :
            tmp = ListNode(count % 10)
            tmp.next = pre.next
            pre.next = tmp
            count = count // 10
        
        return dummy.next
#用链表进行操作
class Solution:
    """
    @param head: the first Node
    @return: the answer after plus one
    """
    def plusOne(self, head):
        # Write your code here
        #对链表进行翻转
        new_head = None
        while head:
            tmp = head.next
            head.next = new_head
            new_head = head
            head = tmp
        
        head = new_head
        carry = 1
        new_head = None
        while head:
            tmp = head.next
            head.next = new_head
            new_head = head
            head = tmp
            val = new_head.val + carry
            carry = val // 10
            new_head.val = val % 10
        
        if carry:
            node = ListNode(carry)
            node.next = new_head
            new_head = node
        
        return new_head

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81748269
今日推荐