チェーンテーブル-複雑なチェーンテーブルのコピー
2094 ワード
複雑なチェーンテーブルのコピー.1つのチェーンテーブルの各ノードには、nextポインタが次のノードを指し、randomポインタがこのチェーンテーブルのランダムノードまたはNULLを指しています.このチェーンテーブルのコピーを実現し、コピー後の新しいチェーンテーブルに戻る必要があります.
//ps:複雑なチェーンテーブルの構造struct ComplexNode{int_data;//データstruct ComplexNode*_next;//次のノードを指すポインタstruct ComplexNode*_random;//ランダムノードを指す(チェーンテーブル内の任意のノードor空であってもよい)};
分析:
ノードを個別に順次コピーした後、randomポインタを順次後ろに移動します.元のノードを削除してコピーしたノードを順次リンクする
//ps:複雑なチェーンテーブルの構造struct ComplexNode{int_data;//データstruct ComplexNode*_next;//次のノードを指すポインタstruct ComplexNode*_random;//ランダムノードを指す(チェーンテーブル内の任意のノードor空であってもよい)};
分析:
ノードを個別に順次コピーした後、randomポインタを順次後ろに移動します.元のノードを削除してコピーしたノードを順次リンクする
ComplexNode* CopyList(ComplexNode* plist)
{
if (plist == NULL)
{
return NULL;
}
ComplexNode* newnode = NULL;
ComplexNode* tmp = plist;
//1.1
while (tmp != NULL)
{
newnode = (ComplexNode*)malloc(sizeof(ComplexNode));
newnode->_data = tmp->_data;
newnode->_next = tmp->_next;
newnode->_random = NULL;
tmp->_next = newnode;
tmp = tmp->_next->_next;
}
//1.2 random
tmp = plist;
newnode = plist->_next;
while (tmp != NULL)
{
if (tmp->_random != NULL)
{
newnode->_random = tmp->_random->_next;
}
tmp = tmp->_next->_next;
if (tmp)
{
newnode = tmp->_next;
}
}
//2.
ComplexNode* res = plist->_next;
tmp = plist;
tmp->_next = tmp->_next->_next;
tmp = tmp->_next;
newnode = plist->_next;
while ((tmp->_next != NULL)&&(tmp != NULL))
{
newnode->_next = newnode->_next->_next;
tmp->_next = tmp->_next->_next;
tmp = tmp->_next;
newnode = newnode->_next;
}
return res;
}
void Test1()
{
ComplexNode* list = NULL;
ComplexNode* node1 = PushBack(&list, 2);
ComplexNode* node2 = PushBack(&list, 5);
ComplexNode* node3 = PushBack(&list, 6);
node1->_random = node3;
node2->_random = node1;
node3->_random = node2;
ComplexNode* res = CopyList(list);
}