簡體   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