首页 > 解决方案 > 如何组合或合并 2 个链接列表以创建新列表?

问题描述

我正在尝试获取两个链表“list_1”和“list_2”,然后将它们组合起来放入“list_3”。我创建了两个列表,但似乎无法弄清楚如何组合它们。我添加的代码是我创建列表的方式。非常新的指针和链表,所以任何帮助将不胜感激,谢谢!

struct node
{
    int data;
    node *next;
};

class List
{
    public:
        node *head, *tail;
    List()
    {
        head = NULL;
        tail = NULL;
    }

    void add_node(int n)
    {
        for(int i = 1; i <= 1; i++)
        {
            node *temp = new node;
            temp -> data = n;
            temp -> next = NULL;

            if(head == NULL)
            {
                head = temp;
                tail = temp;
            }
            else{
                tail -> next = temp;
                tail = tail -> next;
            }
        }
    }

标签: c++linked-listsingly-linked-list

解决方案


您必须“重新布线”它们。head列表 B 的对象应该重新连接到tail列表 A 的对象,这样您就可以删除List列表 B 的对象,但不会删除其成员。引入新的方法merge(List* list)参数,并重新连接this->taillist->head,并更新this->taillist->tail


推荐阅读