使用Stack反转Linkedlist:输出错误

时间:2016-05-16 14:09:35

标签: c++ templates

使用堆栈的反向列表
我是C ++模板的新手,并通过小编程学习它。 我绝对不会理解逻辑上的错误。 这是代码。

 .
 .
 .
 .



template<typename T>
void Display(node<T> *front)
{
    node<T> *temp = front;
    while (temp != NULL)
    {
        cout << temp->data << "  ";
        temp = temp->next;
    }
    cout << endl;
}

template<typename T>
void Reverse(node<T> *front)
{
    node<T> *temp = front;
    stack< node<T>* > s;
    while (temp != NULL)
    {
        s.push(temp);
        temp = temp->next;
    }
    node<T> *curr = s.top();
    front = curr;
    s.pop();
    while (!s.empty())
    {
        curr->next = s.top();
        s.pop();
        curr = curr->next;
    }
    curr->next = NULL;
}

int main()
{
    node<int> *front = NULL;
    int size, no;
    cout << "Enter the size of list ";
    cin >> size;
    for (int i = 1; i <= size; i++)
    {
        cout << "Enter the " << i << " element " << endl;
        cin >> no;
        front = new node<int> ( no , front);
    }
    Display(front);
    Reverse(front);
    cout << " Reverse of the linklist is "<<endl;
    Display(front);
    _getch();
    return 0;
}

输出:
输入清单的大小:3
输入1个元素:2
输入2个元素:4
输入3个元素:6
6 4 2
链接列表的反向是
6

1 个答案:

答案 0 :(得分:0)

您保持指向成为尾部的节点的指针:

enter image description here

您可以将node包裹在list中,知道如何正确地反转元素的顺序,并知道哪个是头部。还将管理为节点分配的内存,这样你就不会有memleaks。