lintcode练习-786. Linked List Weighted Sum In Reverse Order

786. Linked List Weighted Sum In Reverse Order

Given a linked list, find the weighted sum in reverse order. The weight is the number of nodes up to the end of the queue.

样例

Given 3 -> 2 -> 5 -> 1
return 29(3 * 4 + 2 * 3 + 5 * 2 + 1)

实现代码:

class Solution:
    """
    @param head: the given linked list
    @return:  the weighted sum in reverse order
    """
    def weightedSumReverse(self, head):
        # write your code here
        #统计链表的长度
        n = 0
        pre = head
        while pre:
            n += 1
            pre = pre.next
        
        #计算链表的加权和
        sum_link = 0
        
        while head and n:
            sum_link += head.val * n
            n -= 1
            head = head.next
        
        return sum_link

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/81668035