views:

37

answers:

2

Hi all,

I'm doing some tests to a LinkedList, that has two pointers: one point to the next item in the list and the other point to a random node within the list.

Here is the code:

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)
  };
} 

I'm getting the following errors (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 '}'

Thanks.

+6  A: 

This bit is not valid C++:

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

Change it to this:

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

return pNode;
Igor Zevaka
Would be nice syntax tho :)
Merlyn Morgan-Graham
Indeed it would. After a while one gets spoilt by C# syntactic sugar.
Igor Zevaka
Looks like Java.
Thomas Matthews
+1  A: 

Add a constructor to Node:

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

   // ...
};

then

return new Node(a, b, c);
dash-tom-bang