使用堆栈的反向列表
我是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