首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++合并链表问题

C++合并链表问题
EN

Stack Overflow用户
提问于 2020-11-15 14:00:17
回答 1查看 38关注 0票数 0

所以我是C++的初学者,我有一个创建链表的学校项目,我现在正在研究merge方法,我不确定为什么它不能工作。我发现问题出在第二个if循环中,它不是更改head_列表节点,而是更改list1列表,我不知道它为什么要这样做

代码语言:javascript
复制
template <typename T>
bool List342<T>::Merge(const List342<T>& list1) {
    if (head_ == nullptr) {
        head_ = list1.head_;
        return true;
    }
    if (list1.head_ == nullptr) {
        return false;
    }
    Node<T>* l1_ptr = list1.head_;
    Node<T>* head_ptr = head_;
    while (l1_ptr != nullptr && head_ptr != nullptr) {
        if (*head_ptr->data == *l1_ptr->data) {
            l1_ptr = l1_ptr->next;
            head_ptr = head_ptr->next;
        }
        else if (*head_ptr->data <= *l1_ptr->data) {
            Node<T>* temp = head_ptr->next;
            head_ptr->next = l1_ptr;
            l1_ptr->next = temp;
            l1_ptr = l1_ptr->next;
            head_ptr = head_ptr->next;
        }
    }
    return true;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-15 14:42:31

我发现使用链表在列表迭代器上使用引用和递归更容易。此版本确保第二个链表处于有效状态(尽管可能已更改),并且不会分配新的内存。

代码语言:javascript
复制
template <class T>
bool List342<T>::Merge(List342<T>& list1) {
  merge(head_, list1.head_);
}

template <class T>
void merge(List342<T>::Node*& head, List342<T>::Node*& head_o) {
  if (head_o == nullptr)
      return;

  if (head == nullptr) {
    head = head_o;
    head_o = nullptr;
    return;
  }

  if (*head->data <= *head_o->data) {
    merge(head->next, head_o);
  } else {
    // steal Node from right list1                                                                                             
    auto* next = head->next;
    auto* next_o = head_o->next;
    head->next = head_o;
    head_o->next = next;
    head_o = next_o; // this works because head_o is a reference                                                               
    merge(head->next, head_o);
  }
}

我认为这类代码使得争论每种情况下发生的事情变得容易得多。如果你有什么问题,请告诉我。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64841633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档