[英]Check whether LinkedList is an SubList
public class CharNode {
private char _data;
private CharNode _next;
public CharNode(char dat, CharNode n) {
_data = dat;
_next = n;
}
public char getData() {
return _data;
}
public CharNode getNext() {
return _next;
}
public void setData(char d) {
_data = d;
}
public void setNext(CharNode node) {
_next = node;
}
}
public class CharList {
private CharNode _head;
public CharList( ) {
_head = null;
}
public CharList (CharNode node) {
_head = node;
}
public int subList(IntList list)
{
int count = 0;
IntNode listNode = _head;
IntNode otherListNode = list._head; ;
while (listNode != null)
{
if (otherListNode == null)
otherListNode = list._head;
if (listNode.getValue() == otherListNode.getValue())
{
listNode = listNode.getNext();
otherListNode = otherListNode.getNext();
if (otherListNode == null)
count++;
}
else
{
listNode = listNode.getNext();
otherListNode = list._head;
}
}
return count;
}
}
我需要編寫函數public int subList (CharList list)
來獲取list
並返回該列表存在的次數。 例如,如果我的列表是abcdabge
並且作為參數接收的列表是ab
,它將返回2。 該方法應盡可能高效。
目前,我的問題是我不知道如何同時遍歷兩個列表以比較值
要同時遍歷兩個列表:
public bool equalsSubList(CharNode other) {
CharNode node1 = this;
CharNode node2 = other;
while (node1 != null && node2 != null) {
// compare data from both nodes
node1 = node1.getNext();
node2 = node2.getNext();
}
// return true if all nodes where compared and are equal
}
對於完整的解決方案,您將必須循環遍歷您的列表一次,而其他列表則要進行多次匹配。 讓我們以abcdabge
與ab
相比為例:
other | this
|
a b | a b c d a b g e
^ | ^ (match a, go to next in both lists)
a b | a b c d a b g e |
^ | ^ (match a b, counter is 1, go to next this, restart other)
a b | a b c d a b g e
^ | ^ (does not match a, go to next this, restart other)
a b | a b c d a b g e
^ | ^ (does not match a, go to next this, restart other)
a b | a b c d a b g e
^ | ^ (match a, go to next in both lists)
a b | a b c d a b g e
^ | ^ (match a b, counter is 2, go to next this, restart other)
a b | a b c d a b g e
^ | ^ (does not match a, go to next this, restart other)
a b | a b c d a b g e
^ | ^ (does not match a, go to next this, restart other)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.