【发布时间】:2011-10-10 00:06:08
【问题描述】:
我正在尝试为数据结构类实现一个链表,但我在算法的搜索部分遇到了一些困难。
下面是有问题的代码,我尝试按照 MIT 算法介绍文本中的伪代码来实现它:
//
// Method searches and retrieves a specified node from the list
//
Node* List::getNode(unsigned position)
{
Node* current = m_listHead;
for(unsigned i = m_listSize-1; (current != 0) && (i != position); --i)
current = current->next;
return current;
}
程序中此时的头是第4个节点,其中包含int 5的值。问题似乎出在for循环的主体中,其中指向节点对象的指针被分配给了next节点。但这超出了节点的头部,因此它本质上指向内存中的某个随机位置(这是有道理的)。
在这种情况下,算法不应该移动到前一个节点而不是下一个节点吗?下面是伪代码:
LIST-SEARCH(L, k)
x <- head
while x != NIL and key != k
do x <- next[x]
return x
另外,这里是我的链表实现的头文件。为了简单起见,我还没有尝试以模板形式实现它:
#ifndef linkList_H
#define linkList_h
//
// Create an object to represent a Node in the linked list object
// (For now, the objects to be put in the list will be integers)
//
struct Node
{
// nodes of list will be integers
int number;
// pointer to the next node in the linked list
Node* next;
};
//
// Create an object to keep track of all parts in the list
//
class List
{
public:
// Contstructor intializes all member data
List() : m_listSize(0), m_listHead(0) {}
// methods to return size of list and list head
Node* getListHead() const { return m_listHead; }
unsigned getListSize() const { return m_listSize; }
// method for adding a new node to the linked list,
// retrieving and deleting a specified node in the list
void addNode(Node* newNode);
Node* getNode(unsigned position);
private:
// member data consists of an unsigned integer representing
// the list size and a pointer to a Node object representing head
Node* m_listHead;
unsigned m_listSize;
};
#endif
addNode方法的实现:
//
// Method adds a new node to the linked list
//
void List::addNode(Node* newNode)
{
Node* theNode = new Node;
theNode = newNode;
theNode->next;
m_listHead = theNode;
++m_listSize;
}
【问题讨论】:
-
列表是双向链接的吗?记忆中的样子是什么?
-
我认为问题可能出在 addNode 成员函数中。请提供该代码,以便我们确保正确构建列表。
-
是的,我认为这应该是双向的。我还没有将前一个节点字段添加到元素中。不知道该怎么做。
标签: c++ algorithm data-structures linked-list