可能重复:
Copy a linked list链表问题
计算器您好!我想了解更多关于链接列表,所以我想创建一个深层复制链接列表的函数。我已经掌握了这个。难点在于输入列表将包含引用列表中其他随机节点的节点。
第一个问题是我不知道如何在列表中创建“随机”节点。截至目前,我只有'随机'节点等于'下一个'节点。
例如... pNext引用下一个值,但pReference将引用列表中的随机节点。像pReference 1参考文献3,2参考文献4,3参考文献1和4参考文献1.
第二个问题是我的代码应对'随机'节点值,但它依赖于原始副本。我希望它是一个深层复制,而不依赖于原始文件。
#include <iostream>
#include <stdio.h>
using namespace std;
struct Node
{
int Number; // An integer value.
Node *pNext; // A pointer to the next node within the list.
Node *pReference; // A pointer to a random node within the list.
};
void push(Node** head, int data, Node* reference)
{
Node* newNode = new Node;
newNode->Number = data;
newNode->pNext = *head;
newNode->pReference = reference;
*head = newNode;
}
Node* DuplicateLinkedList(Node *head)
{
Node* current = head;
Node* newHead = NULL;
Node* newTail = NULL;
while(current != NULL)
{
if(newHead == NULL)
{
push(&newHead, current->Number, (current->pReference));
newTail = newHead;
}
else
{
push(&(newTail->pNext),current->Number, (current->pReference));
newTail = newTail->pNext;
}
current = current->pNext;
}
return newHead;
}
int main()
{
Node* headOfList= NULL;
//Creating List for verification.
for(int i=6; i>=1;i--)
{
push(&headOfList, i, headOfList);
}
//Call duplicate function.
Node* copiedList = DuplicateLinkedList(headOfList);
//Output for verification
cout << endl << "Original: " << endl;
while(headOfList != NULL)
{
cout << "Number: " << headOfList->Number << " ";
cout << "pNext: " << headOfList->pNext << " ";
cout << "pReference: " << headOfList->pReference << " " << endl;
headOfList = headOfList->pNext;
}
cout << endl << endl;
cout << endl << "Copied: " << endl;
while(copiedList != NULL)
{
cout << "Number: " << copiedList->Number << " ";
cout << "pNext: " << copiedList->pNext << " ";
cout << "pReference: " << copiedList->pReference << " " << endl;
copiedList = copiedList->pNext;
}
cout << endl << endl;
system("pause");
}
你是什么意思的“随机节点”? – 2010-08-11 21:47:54
@David Thornley:这是一个比较常见的面试问题。随机节点是同一列表中的任何一个列表元素(节点)。 – 2010-08-11 21:56:46
@Moron:是的。投票关闭。但是,10分钟的工作让人分心。 – 2010-08-11 22:20:17