如何使用字符串更改此插入功能以在链接列表中工作

How can I change this insert function to work in a linked list using strings?

本文关键字:链接 列表 工作 功能 插入 字符串 何使用      更新时间:2023-10-16

这是我在stackoverflow上发布的第一个问题,所以请原谅我是否有点不稳。

对于我的计算机科学课,我们正在使用双链接列表进行当前作业。所需的功能之一是插入功能。

我实际上在本周早些时候在Stackoverflow上找到了一个插入功能,但是它设置为使用主文件内部的结构,而不是像此项目所使用的单独的类文件。我认为该功能可以正常工作,但是我不确定需要进行哪些更改,以便可以与类文件一起使用。

linkedlist.h成员数据

private:
    Node *head, *tail;
    mutable Node *it;
    int count;

插入功能

bool LinkedList::insert(const string & str) const
{
    LinkedList * tempVar;
    if (hasMore) {
        resetIterator();
    }
    else {
        Node * temp = new Node;
        //temp = str;
        temp->data = str;
        temp->next = it;
        temp->prev = nullptr;
        it->prev = temp;
        it = temp;
    }
    if (it != nullptr) {
        Node * current = it;
        Node * previous = nullptr;
        Node * tempNode = nullptr;
        while (current->next != nullptr) {
            tempNode = current->next;
            if (current->data > tempNode->data) {
                swap(current->data, tempNode->data);
            }
            else {
                previous = current;
                current = current->next;
            }
        }
        tempVar->count += 1;
    }
    return false;
}

由于不知道需要哪些更改,我还无法对其进行测试,但是该函数应插入参数中的字符串中的字符串中的链接列表,并以词典样式对其进行排序。现在唯一的错误是temp = str;不起作用,我不完全确定我需要做什么才能使它起作用。

尝试更多类似的东西:

bool LinkedList::insert(const string & str)
{
    Node * current = head;
    while ((current) && (current->data < str))
        current = current->next;
    Node *newNode = new Node;
    newNode->data = str;
    newNode->next = nullptr;
    newNode->prev = nullptr;
    if (current)
    {
        if (current->previous)
        {
            current->previous->next = newNode;
            newNode->previous = current->previous;
        }
        current->previous = newNode;
        newNode->next = current;
        if (current == head)
            head = newNode;
    }
    else
    {
        if (!head)
            head = newNode;
        if (tail)
        {
            tail->next = newNode;
            newNode->previous = tail;
        }
        tail = newNode;
    }
    count += 1;
    return true;
}

话虽如此,您确实应该使用标准的std::list容器,而不是手动实现双连锁列表。