简体   繁体   English

Java 中的链表 - 比较两个列表

[英]Linked list in Java - comparing two lists

I need to create a recursive method in java which checks two Char lists.我需要在 java 中创建一个递归方法来检查两个字符列表。 If the second list includes all the chars in the first list at least once and in the same order it should return true, else it should return false.如果第二个列表包含第一个列表中的所有字符至少一次并且以相同的顺序它应该返回 true,否则它应该返回 false。 for example:例如:

List 1: "abbcd"(every char in a node), List 2: "abbcccddd"(every char in node) This should return true.列表 1:“abbcd”(节点中的每个字符),列表 2:“abbcccddd”(节点中的每个字符)这应该返回 true。

Example 2: "abbcd", List 2: "abcd" this should return false.示例 2:“abbcd”,列表 2:“abcd”这应该返回 false。

I have some ideas but can't reach a definite solution.我有一些想法,但无法得出明确的解决方案。 Ideas anyone?任何人的想法?

I'll assume that you use the usual node structure with a data element and a reference to the next node.我假设您使用带有数据元素和对下一个节点的引用的通常节点结构。 Then one can define the function as follows:然后可以定义 function 如下:

  • contains(null, haystack) = true (since every string contains the empty string) contains(null, haystack) = true (因为每个字符串都包含空字符串)

  • contains(pattern, null) = false (since the empty string doesn't contain any patterns) contains(pattern, null) = false (因为空字符串不包含任何模式)

  • contains(pattern, haystack) = contains(pattern.next, haystack.next) if pattern.data = haystack.data (we found a match and proceed to the next item in both lists) contains(pattern, haystack) = contains(pattern.next, haystack.next) if pattern.data = haystack.data (我们找到匹配项并继续处理两个列表中的下一项)

  • contains(pattern, haystack) = contains(pattern.next, haystack.next) else (we found no match and try it with the next character in the haystack) contains(pattern, haystack) = contains(pattern.next, haystack.next) else (我们没有找到匹配项并尝试使用 haystack 中的下一个字符)

The in order requirement also simplifies the problem.有序的要求也简化了问题。

Consider that both lists are iterated over at the same time with slightly different advancing rules:考虑到两个列表同时迭代,推进规则略有不同:

  1. When is the list "to find" advanced to the next node? “要查找”列表何时推进到下一个节点?
  2. When is the list which may contain the "to find" list advanced to the next node?可能包含“查找”列表的列表何时推进到下一个节点?
  3. At what point is it determined that the "to find" list is not contained in the other?在什么时候确定“要查找”列表不包含在另一个列表中?
  4. At what point is a match determined?比赛在什么时候确定?
  5. How can it be done iterating each list?如何迭代每个列表? How can it be done recursively?如何递归完成?

Happy coding.快乐编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM