鏈表—複雜鏈表的複製

複雜鏈表的複製。一個鏈表的每個節點,有一個指向next指針指向下一個節點,還有一個random指針指向這個鏈表中的一個隨機節點或者NULL,現在要求實現複製這個鏈表,返回複製後的新鏈表。

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章