单链表的问题с++

问题描述 投票:0回答:1

我有一个执行以下任务的代码:逐行输入字符到点,然后显示一个列表。我需要添加这样一个方法,以便在调用它时,列表中的所有字符都以相反的顺序补充(例如,有一个 abс. 列表应该变成 abс.сba)。您无法展开该列表。该方法应基于以下原则:我们从第一个元素开始再次遍历列表,并每次在该点后面添加一个元素(首先是 abс.a,然后是 abс.ba,然后是 abс.сba)。我尝试编写添加元素函数,但我最终对此感到困惑,或者我捕获了一个空输出的无限循环,或者反之亦然,具有无限输出,或者仅输出第一个字符

这是我的代码

#include <iostream>
#include <windows.h>

struct element {
    char x;
    element* Next;
};

class List {
    element* Head;
public:
    List() {
        Head = NULL;
    }
    ~List();

    void Add(char x, element*& Head);
    void Show(element* Beg);
    void AddElements(element* beg, element*& Head);

};

List::~List() {
    while (Head != NULL) {
        element* temp = Head->Next;
        delete Head;
        Head = temp;
    }
}


void List::Add(char x, element*& Head) {
    element* temp = new element;
    temp->x = x;
    temp->Next = NULL;
    Head->Next = temp;
    Head = temp;
}


void List::Show(element* beg) {
    element* temp = beg;
    while(temp != NULL) {
        std::cout << temp->x << "";
        temp = temp->Next;
    }
    Head = beg;
}

void List::AddElements(element* beg, element*& Head) {
    element* temp1 = beg;
    element* temp2 = Head;
    element* temp0 = temp1;
    temp2->Next = temp0;
    while (temp1 != temp2) {
        temp0->Next = temp2->Next;
        temp0 = temp1;
        temp2->Next = temp0;
        
        if (temp1->Next != NULL) {
            temp1 = temp1->Next;
        }
    }

}

int main() {
    system("chcp 1251");
    std::cout << "Односвязный список." << std::endl;
    char x;
    List lst;
    element* H = new element;
    element* beg = H;
    std::cout << "Введите символ: "; std::cin >> x;
    H->x = x;
    H->Next = NULL;
    while (x != '.') {
        std::cin >> x;
        lst.Add(x, H);
    }
    lst.AddElements(beg, H);
    std::cout << "Результат: ";
    lst.Show(beg);
    
    return 0;
}

我希望从abs列表中创建一个函数。将创建 abс.сba 列表并输出它(

c++ singly-linked-list
1个回答
0
投票

您遇到的问题似乎是由于您的

AddElements
方法中链接列表的操作不正确。

任务是反转字符的顺序并将它们添加到列表的末尾。这可以通过遍历列表,将字符存储在堆栈中,然后将堆栈中的反向字符填充回列表中来实现。

void List::AddElements(element* beg) {
    std::stack<char> s;
    element* temp = beg;
    while(temp != NULL) {
        s.push(temp->x);
        temp = temp->Next;
    }
    while(!s.empty()) {
        Add(s.top(), Head);
        s.pop();
    }
}

这是发生的事情:

  • 从头到尾遍历列表,将每个字符压入堆栈。这是因为堆栈遵循后进先出 (LIFO) 协议,这意味着最后添加的元素将是第一个被删除的元素。这本质上颠倒了字符的顺序。
  • 从堆栈中弹出每个字符并将其添加到列表末尾 使用
    Add
    方法。
© www.soinside.com 2019 - 2024. All rights reserved.