【问题标题】:Can someone explain the algorithm?有人可以解释一下算法吗?
【发布时间】:2020-07-04 19:24:40
【问题描述】:

我需要参数为(LinkedList 一,LinkedList 二)的函数

那么,如何分别设置/定义列表的头部和电流??

我不知道为什么这个问题被关闭了。 但是我是java新手,需要解决这个问题,所以有人可以帮忙吗???

要检查一个列表是否是另一个列表的子集,我有来自 GeeksforGeeks 的代码

这里是代码如果我们在参数中传递节点喜欢(节点一,节点二)但我想要参数为(链表一,喜欢的列表二)所以任何人都可以解释算法这样做吗???

static boolean checkSubSet(Node first, Node second) { 
    Node ptr1 = first, ptr2 = second; 
  
    // If both linked lists are empty, 
    // return true 
    if (first == null && second == null) 
        return true; 
  
    // Else If one is empty and  
    // other is not, return false 
    if (first == null || 
       (first != null && second == null)) 
        return false; 
  
    // Traverse the second list by  
    // picking nodes one by one 
    while (second != null) 
    { 
        // Initialize ptr2 with  
        // current node of second 
        ptr2 = second; 
  
        // Start matching first list  
        // with second list 
        while (ptr1 != null) 
        { 
            // If second list becomes empty and  
            // first not then return false 
            if (ptr2 == null) 
                return false; 
  
            // If data part is same, go to next 
            // of both lists 
            else if (ptr1.data == ptr2.data) 
            { 
                ptr1 = ptr1.next; 
                ptr2 = ptr2.next; 
            } 
  
            // If not equal then break the loop 
            else break; 
        } 
  
        // Return true if first list gets traversed 
        // completely that means it is matched. 
        if (ptr1 == null) 
            return true; 
  
        // Initialize ptr1 with first again 
        ptr1 = first; 
  
        // And go to next node of second list 
        second = second.next; 
    } 
    return false; 
} 

但是如何通过将实际的链表作为参数传递给 eg 来做同样的事情

static boolean checkSubSet(Node first, Node second){}

我想做这个而不是这个

static boolean checkSubSet(LinkedList<Integer> list1,LinkedList<Integer> list2){} 

【问题讨论】:

  • 它不是我的代码。这就是为什么我说“我有这个代码”而不是“我写了这个代码”。无论如何感谢您指出,我编辑了问题并提供了参考。

标签: java data-structures linked-list abstract-data-type


【解决方案1】:

您正在尝试重构您的代码,使其接受java.util.LinkedList 作为参数。好吧,我看到您的代码来自geeksforgeeksgeeksforgeeks 假设您有自己的链表实现。它还假设您可以访问链表节点的nextdata 部分。不幸的是,java LinkedList 没有公开这些,因此您的代码对您的问题没有用处。

您需要为 Java LinkedList 设计一个新算法。因为LinkedList 不是Set。在LinkedList 上执行集合函数意义不大。然而, 如果你真的需要,你可以使用类似的东西:

return new HashSet(a).containsAll(new HashSet(b));

或者,遍历列表以获得你想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 2016-12-12
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多