【问题标题】:How to compare 2 linked lists in c++ and put matching data into another linked list如何在c ++中比较2个链表并将匹配的数据放入另一个链表
【发布时间】:2020-02-05 04:07:37
【问题描述】:

我想比较两个包含书名的链接列表,然后创建一个新的链接列表,其中仅包含原始列表中的匹配标题。目前我已经创建了两个链表,并且可以按字母顺序输出。当我尝试比较并创建具有匹配标题的更新列表时,问题就出现了。

我试图创建一个递归函数,它接受两个列表作为参数,如果标题不匹配,它将调用自身并将第二个列表移动到下一个节点。

如果它们都匹配,那么它会再次调用自己,但会将两个列表都向上移动一个节点。

我在使用链表和递归方面还很陌生,但我觉得我走在正确的轨道上。我所有的其他函数都在工作,我只是不知道如何使它工作以及如何在我的主函数中调用它。

Node *compare(Node *h, Node *j) {
  Node* h_curr = h;
  Node* j_curr = j;
  Node* new_node;
  Node* updated_list = NULL;
  while ((h_curr->next != NULL) || (j_curr->next != NULL)) {
    if (h_curr->data != j_curr->data) { // if not equal, then move j_head to the next link 
      compare(h_curr, j_curr->next);
        //j_curr = j_curr->next;
    }
    else {
      updated_list->data = h_curr->data;
      new_node = newNode(updated_list->data);
      return updated_list;
      updated_list = updated_list->next;

      compare(h->next, j->next);
    }

  }
  return NULL;
}

【问题讨论】:

  • 按字母顺序输出我们可以假设数据已排序吗?未分类的数据很严重。 N 平方毛。
  • 是的,两个列表都在被调用到比较函数之前进行了排序。
  • 一种更简洁的迭代方式是通过“merge”函数(在merge_sort中使用):geeksforgeeks.org/merge-two-sorted-arrays

标签: c++ recursion linked-list


【解决方案1】:
#include<string>
#include<iostream>

//assumed node structure
struct Node{

    Node(std::string str, Node* ptr = nullptr):data(str), next(ptr){}

    std::string data{};
    Node* next{};

};

//The following is your rucresive function
void compare(Node* & first, Node* & second, Node* & match) {

    if(!first || !second ) return;//base case

    if ( first -> data < second -> data) compare(first -> next, second, match ); 
    else if ( first -> data > second -> data) compare(first , second -> next, match); 
    else{//match found
        match = new Node{ first -> data};
        compare(first , second -> next, match -> next); 
    }
}

//To disply the result (recursive function)
void display(Node* & root){

    if(!root) return;
    std::cout<<root->data<<" ";
    display( root-> next);

}


//To test
int main(){

    Node* first = new Node{"aaa"};
    first->next=new Node{"ccc"};
    first->next->next=new Node{"ccc1"};
    first->next->next->next=new Node{"ccc3"};
    first->next->next->next->next=new Node{"ccc4"};
    first->next->next->next->next->next=new Node{"ddd"};


    Node* second = new Node{"baaa"};
    second->next=new Node{"ccc"};
    second->next->next=new Node{"ccc1"};
    second->next->next->next=new Node{"ccc2"};
    second->next->next->next->next=new Node{"ccc4"};

    Node* res;
    compare(first, second, res);
    display(res);


}

【讨论】:

  • 似乎奏效了!我在争论是否应该为函数添加第三个参数,所以我很高兴看到我的想法是正确的。谢谢!
  • @AlexHernandez 欢迎您。你也可以使用只有两个参数的函数,然后在新参数中定义第三个参数后,使用新参数调用解决方案中的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多