まず、OOPに頭を悩ませていないと言うことから始めます。
文字列内の各単語を反復処理し、リンクリストに含まれているかどうかを確認し、含まれていない場合はノードとして追加するか、リストに含まれている場合は既存のノードの数を増やすルーチンが必要です。
これが私が持っているものです:
private void CountWords(string cleanString)
{
WordNode nextNode, prevNode;
WordNode addNode;
foreach (string stringWord in cleanString.Split(' '))
{
if (head == null)
{
// No items in list, add to the beginning
addNode = new WordNode(stringWord);
head = addNode;
}
else
{
if (String.Compare(stringWord, head.Word) < 0)
{
// If stringWord belongs at the beginning of the list, put it there
addNode = new WordNode(stringWord);
addNode.NextWord = head;
head = addNode;
}
else if (String.Compare(stringWord, head.Word) == 0)
{
// If stringWord is equal to head.Word, increase count
addNode.Count += 1;
}
else
{
prevNode = head;
nextNode = head.NextWord;
// If it doesn't belong at the beginning, cycle through the list until you find where it does belong
while ((nextNode != null) && (String.Compare(nextNode.Word, addNode.Word) < 0))
{
prevNode = nextNode;
nextNode = nextNode.NextWord;
}
if (nextNode == null)
{
prevNode.NextWord = addNode;
}
else
{
prevNode.NextWord = addNode;
addNode.NextWord = nextNode;
}
}
}
}
}
これの前に、私はaddNode = new WordNode(stringWord);を試みていました。「文字列内の各単語」ループの各反復の開始時に、クラスが再定義され、カウントが1にリセットされます。現在、addNode.Count + = 1であるため、カウントを増やすことはできません。は未定義です。stringWordがリンクリストに含まれているかどうかを確認し、含まれている場合はstringWord.countを1つインクリメントできることを期待していましたが、エラーが発生します。
これを今見て、私はaddNode.Count + = 1;を考えています。その数行下のwhileループに属しています...
これが私のWordNodeクラスです:
class WordNode
{
// constants
// variables
private string data; // this is our only data, so also key
private int count;
private WordNode next; // this is reference to next Node
// constructors
public WordNode(string newValue)
{
Word = newValue;
count = 1;
NextWord = null;
}
// methods
public string Word
{
get
{
return data;
}
set
{
data = value;
}
}
public int Count
{
get
{
return count;
}
set
{
count = value;
}
}
public WordNode NextWord
{
get
{
return next;
}
set
{
next = value;
}
}
}
これを試して:
private void CountWords(string cleanString)
{
foreach (string stringWord in cleanString.Split(' '))
{
if (head == null)
{
head = new WordNode(stringWord);
}
else
{
var last = (WordNode)null;
var current = head;
do
{
if (current.Word == stringWord)
{
break;
}
last = current;
current = current.NextWord;
} while (current != null);
if (current != null)
{
current.Count++;
}
else
{
last.NextWord = new WordNode(stringWord);
}
}
}
}
そして、代替手段はlinqを使用することです。
var query =
cleanString
.Split(' ')
.ToLookup(x => x)
.Select(x => new
{
Word = x.Key,
Count = x.Count(),
});
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加