在测试LinkedLists时编译VS2010中的错误

时间:2010-08-23 22:58:07

标签: c++ data-structures linked-list

我正在对LinkedList进行一些测试,它有两个指针:一个指向列表中的下一个项目,另一个指向列表中的随机节点。

以下是代码:

struct Node
{
   Node* pNext;      // a pointer to the next node in the list
   Node* pReference; // a pointer to a random node within the list
   int   number;     // an integer value
};

/**
 * This version works for small/medium lists, using recursion.
 */

Node* duplicateList(Node* n)
{
  if (n == NULL) return NULL;

  return new Node()
  {
     number  = n->number,
     pNext  = duplicateList(n->pNext),
     pReference = duplicateList(n->pReference)
  };
} 

我收到以下错误(VS2010):

d:\dornad\my documents\visual studio 2010\projects\test\test.cpp(21): error C2143: syntax error : missing ';' before '{'

1>d:\dornad\my documents\visual studio 2010\projects\test\test.cpp(22): error C2065: 'number' : undeclared identifier

1>d:\dornad\my documents\visual studio 2010\projects\test\test.cpp(23): error C2065: 'pNext' : undeclared identifier

1>d:\dornad\my documents\visual studio 2010\projects\test\test.cpp(24): error C2065: 'pReference' : undeclared identifier

1>d:\dornad\my documents\visual studio 2010\projects\test\test.cpp(25): error C2143: syntax error : missing ';' before '}'

感谢。

2 个答案:

答案 0 :(得分:6)

这个位无效C ++:

return new Node()
{
  number  = n->number,
  pNext  = duplicateList(n->pNext),
  pReference = duplicateList(n->pReference)
};

将其更改为:

Node* pNode = new Node();
pNode->number  = n->number;
pNode->pNext  = duplicateList(n->pNext);
pNode->pReference = duplicateList(n->pReference);

return pNode;

答案 1 :(得分:1)

向Node添加构造函数:

struct Node
{
   Node(Node* next, Node* ref, int number) : pNext(next), pReference(ref), number(number) { }

   // ...
};

然后

return new Node(a, b, c);