繁体   English   中英

不确定如何反转我的堆栈?

[英]Not sure how to reverse my stack?

我正在尝试编写一个程序,该程序使用链接列表实现堆栈,在输入单词“ 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);
}
int display(node * head)
{
      if(head)
      {
            display(head->next);
            cout<< head->data <<endl;
      }
}

此显示功能将以相反的顺序打印堆栈。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM