2012-03-22 50 views
0

我有2個鏈接列表,並且我想將兩個集合中的元素複製到newSet中,以便我可以刪除新集中的重複值並顯示它。到目前爲止,一切似乎都出錯了,它不會複製這個集合。如何將2個鏈接列表中的元素複製到新鏈接列表中

struct Node *Union(struct Node *Link1, struct Node *Link2) 
{ 

    struct Node * set1 = Link1; 

    struct Node * set2 = Link2; 

    //Creat a new set 
    struct Node * newSet = (struct Node *) malloc(sizeof(struct Node)); 

    while(set1 != NULL && set2 != NULL) 
    { 

     //copy sets to newSet 
     newSet->data = set1->data; 
     newSet->data = set2->data; 
     newSet->next = Union(set1->next, set2->next); 
    } 

    return (newSet); 

} 

任何幫助appriacted

回答

1

你的主要問題是,你分配一個節點的新值然後用名單的頭和推進指針覆蓋它。這意味着你會失去每一個第二個節點。

此外,連接兩個名單是不是真的一個非常適合遞歸,因爲搜索空間不會減少快速(理想人選遞歸,就像一個二進制印章或者多路樹的遍歷,扔掉每次遞歸調用都有大量的搜索空間)。你可以用一些反覆做這樣,(假設升序排列,並採用,因爲它的功課僞代碼):

def union (link1, link2): 
    set1 = link1, set2 = link2 
    headnode = NULL, tailnode = NULL 

    # Continue until both lists empty. 

    while set1 is not NULL and set2 is not NULL: 
     # Create new node and set next pointer to NULL. 

     newnode = alloc_node() 
     newnode->next = NULL 

     # Select which set will provide the next node. 

     if set1 is NULL: 
      newnode->data = set2->data, set2 = set2->next 
     else if set2 is NULL: 
      newnode->data = set1->data, set1 = set1->next 
     else if set2->data is less than set1->data: 
      newnode->data = set2->data, set2 = set2->next 
     else: 
      newnode->data = set1->data, set1 = set1->next 

     # Add to end of (possibly empty) list. 

     if headnode is NULL: 
      headnode = newnode, tailnode = newnode 
     else: 
      tailnode->next = newnode, tailnode = newnode 

    return headnode 

它主要的工作原理是在做每添加到您的目的地列表節點一個迭代,直到兩個源列表是空的。如果其中一個源列表爲空,它將從另一個列表中選擇下一個節點。

否則,它從當前指針具有最低值的列表中選擇下一個節點。