【发布时间】:2013-11-30 06:42:29
【问题描述】:
我首先要说我还没有完全理解 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); 在每次迭代开始时通过“for each word in string”循环,但这会重新定义类和将计数重置为 1。目前,我无法增加计数,因为 addNode.Count += 1; 未定义。我希望我可以检查 stringWord 是否在链接列表中,如果是,则将 stringWord.count 加一,但这会引发错误。
现在看这个,我认为 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;
}
}
}
【问题讨论】:
标签: c# text-parsing string-parsing singly-linked-list