如何对链表的所有节点中的特定整数变量求和?

我在2个链接列表中有“客户”对象,分别是排队和送达。每个人都有派对规模的变量。服务队列具有随机分配的等待时间。我需要一个求和并返回队列中客户数量的函数。我认为这意味着将等待列表LinkedList中每个Customer对象内指示方大小的整数相加。

我需要一个求和并返回所服务客户总数的函数。这可能意味着将所提供的客户对象的LinkedList中每个客户对象内指示方大小的整数相加。

我不知道以下哪个链接适合我的情况,即何时使用。尽管如此,我还是尝试成功实现了失败。

对于循环: Counting all the nodes in a Linked List

通过迭代和递归: https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/

    /*Returns count of nodes in linked list */
     public int count(){
         int count=0;
         for(Customer n = ???; n != null; n = n.next){count++;}
         return count;
     }
//        /* Returns count of nodes in linked list */
//        public int getLinesize(Customer cust) 
//        { 
//            // Base case 
//            if (cust == null) 
//                return 0; 
//            // Count is this customer plus rest of the list 
//            return 1 + getLinesize(cust.next); 
//        } 
//         
//        /* Wrapper over getLinesize() */
//        public int getcount() 
//        { 
//            return getLinesize(); 
//        }

我没有得到任何结果,因为我无法生成明智的,无语法错误的代码。运行时错误将是进度。

nidi_3 回答:如何对链表的所有节点中的特定整数变量求和?

LinkedList中的客户对象具有先前定义的getWait()getParty()方法,以获取随机分配的等待时间的值和对象的Party变量的大小。

功能必须包含链接列表。

您可以使用LinkedList类的getFirst方法来获取linkedLists中的第一个元素。

您使用累加器变量获取总和。

使用n != null;n = n.next作为停止条件并在for循环中进行迭代。

您从Customer n = (Customer) ll.getFirst()开始。使用n的时间短一些,您需要显式强制转换。可能是因为函数不知道您的两个链接列表都具有客户类型元素。

返回链接列表中的等待总数:

public int sumWait(LinkedList ll){
         int sumWait = 0;
         for(Customer n = (Customer) ll.getFirst(); n != null; n = n.next){
             sumWait = sumWait + n.getWait();
         }
         return sumWait;
     }

返回链表中的参与者总数

     public int sumCust(LinkedList ll){
         int sumCust = 0;
         for(Customer n = (Customer) ll.getFirst(); n != null; n = n.next){
             sumCust = sumCust + n.getParty();
         }
         return sumCust;
     }
本文链接:https://www.f2er.com/3147258.html

大家都在问