[英]Can someone explain the algorithm?
我需要 function 参数为(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;
}
但是如何通过将实际的链表作为参数传递来做同样的事情,例如
static boolean checkSubSet(Node first, Node second){}
而不是这个我想做这个
static boolean checkSubSet(LinkedList<Integer> list1,LinkedList<Integer> list2){}
您正在尝试重构代码,使其接受java.util.LinkedList
作为参数。 好吧,我看到您的代码来自geeksforgeeks 。 geeksforgeeks假设您有自己的链表实现。 它还假设您可以访问链表节点的next
和data
部分。 不幸的是, java LinkedList
没有公开这些,因此您的代码对您的问题没有用处。
您需要为 Java LinkedList
设计一个新算法。 由于LinkedList
不是Set
。 在LinkedList
上执行集合函数并不是很有意义。 但是,如果你真的需要,你可以使用类似的东西:
return new HashSet(a).containsAll(new HashSet(b));
或者,遍历列表以获得您想要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.