【发布时间】:2014-12-14 03:54:52
【问题描述】:
我正在尝试编写一个使用链表实现堆栈的程序,从用户那里接受无限的单词,直到输入单词“end”,将每个单词压入堆栈,向用户打印你完成接受单词和您将要反向列出句子,并将每个单词弹出给用户,以便它们以与输入时相反的顺序出现。 我已经编写了代码,但我认为我的 pop 函数可能有问题,因为它没有以相反的顺序打印。只是我输入信息的顺序,这意味着它没有弹出,对吗?我不知道。
所以我只需要帮助弄清楚如何 - 向用户弹出每个单词,以便它们以与输入时相反的顺序显示
谢谢! 这是我的代码:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:
class node *next;
string data;
};
class stack : public node
{
node *head;
int tos;
public:
stack()
{
tos=-1;
}
void push(string x)
{
if (tos < 0 )
{
head =new node;
head->next=NULL;
head->data=x;
tos ++;
}
else
{
node *temp,*temp1;
temp=head;
tos++;
while(temp->next != NULL)
temp=temp->next;
temp1=new node;
temp->next=temp1;
temp1->next=NULL;
temp1->data=x;
}
}
void display()
{
node *temp;
temp=head;
if (tos < 0)
{
cout <<" stack under flow";
return;
}
while(temp != NULL)
{
cout <<temp->data<< " ";
temp=temp->next;
}
}
void pop()
{
node *temp;
temp=head;
if( tos < 0 )
{
cout <<"stack under flow";
return;
}
tos--;
while(temp->next->next!=NULL)
{
temp=temp->next;
}
temp->next=NULL;
}
};
main()
{
stack s1;
string input;
while (input != "end"){
cout <<"\n enter a element";
cin >> input;
s1.push(input);
}
s1.pop();
s1.display();
exit(0);
return (0);
}
【问题讨论】:
-
如果这应该是一个堆栈,那么你的插入逻辑就没有意义了。堆栈是 LIFO。这意味着您需要在 push 上弄乱的唯一指针是头指针; 永远。你的 node 节点 next-ptr 指向当前的 head,然后 head 被设置为新的节点。
-
(就逆转一切而言。)您所需要的只是一个临时节点。找出向量中有多少条目。然后,你循环。取节点 [0] 并将其分配给 temp。然后取node[last]赋值给node[0],然后设置node[last] = temp.
-
你的问题被标记为 C++ 但你
#include <stdlib.h>和其他东西。在 C++ 中,如果您被允许使用,我们有std::stack<std::string>。 -
还值得注意的是
stack没有继承自node的业务,并且根本不需要tos。您知道在弹出/顶部/显示期间您是否即将下溢堆栈,因为head将为空(即没有可弹出的内容)。
标签: c++ linked-list stack