给定一个链表,求出这个链表的带权和。链表结点的权值指的是该结点到链表尾节点的结点数。
样例
样例1
输入: 3 -> 2 -> 5 -> 1
输出: 29
解释:
(3 * 4 + 2 * 3 + 5 * 2 + 1) = 29
样例2
输入: 1 -> 2 -> 3 -> 4
输出: 20
解释:
(1 * 4 + 2 * 3 + 3 * 2 + 4) = 20
解题思路:
先求链表长度,然后遍历链表。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the given linked list
* @return: the weighted sum in reverse order
*/
public int weightedSumReverse(ListNode head) {
int res = 0;
int lens = listLength(head);
while(lens != 0){
res += head.val * lens;
lens--;
head = head.next;
}
return res;
}
private int listLength(ListNode head){
int lens = 0;
while(head != null){
lens++;
head = head.next;
}
return lens;
}
}

本文介绍了一种计算链表带权和的算法,通过先求链表长度,再遍历链表并计算每个节点的权值,最终得到链表的带权和。样例展示了算法的具体应用。

被折叠的 条评论
为什么被折叠?



