Реализация стека в c ++ с использованием связанного списка - PullRequest
0 голосов
/ 28 сентября 2018
#include<iostream>
#include<cstdlib>
using namespace std;

 struct node
 {
   int data;   //data
   node *next; //link
 };

 class stack // stack using linked list
 {
  public:
  node *top; // top element of stack

  public:
   stack()
   {
     top= NULL;
   }

   void push(int value)
   {
     node *temp  = new node; // create a new node
     temp-> data = value;
     temp-> next = NULL;
   if(top==NULL)          //  stack is empty
    {
      top=temp;
      temp=NULL;
    }
    else
    {
      temp-> next = top;
      top=temp;
      temp=NULL;
    }
  }
  //template <class X>
  void pop()
  {
    if(top==NULL)
    {
      cout<<"\nStackOverflow "<<endl;
      cout<<"Program Terminated "<<endl;
      exit (0);
    }
    else
    {
      top=top->next;
    }

  }

  void display()
  {

    node *temp=new node;
    temp=top;

    while(temp!=NULL)
    {
      cout<<temp->data<<" ";
      temp = temp-> next;
    }
    while(top==NULL)

     { 
        cout<<"\nStack is Empty "<<endl;  
        exit (0);

     }



  }
};

int main()
{
   stack a;

  a.push(5);
  a.display();
  a.push(10);
  a.display();
  a.pop();
  a.pop();
  a.push(20);
  a.display();
  a.pop();
  a.display();
  return 0;
}

Выход этого кода равен 5 10 5 20 Стек пуст.

Какой вывод неправильный, а правильный вывод 5 10 20 Стек пуст ..скажите мне, почему произошли эти ошибки.

Ссылка на код: [ Реализация стека с использованием шаблонов и связанного списка в c ++

Ответы [ 2 ]

0 голосов
/ 28 сентября 2018
a.push(5);     // Stack:  5
a.display();   // Output: new: 5
a.push(10);    // Stack:  10 5
a.display();   // Output: old: 5 new: 10 5
a.pop();       // Stack:  5
a.pop();       // Stack:  empty
a.push(20);    // Stack:  20
a.display();   // Output: old: 5 10 5 new: 20
a.pop();       // Stack:  empty
a.display();   // Output: old: 5 10 5 20 new: 

stack()
{
    top= NULL;  // use initializ list instead of assignment
                // in constructors body
}

->

stack() : top{ nullptr } {}

void pop()
{
    if (top == NULL)
    {
        cout << "\nStackOverflow " << endl;
        cout << "Program Terminated " << endl;
        exit(0);  // don't use exit() in C++ if there are other ways!
    }
    else
    {
        top = top->next; // the memory top pointed to
                         // before the assignment leaks!
    }
}

->

void pop()
{
    if (!top) {
        cout << "Pop on empty stack!\n";
        return;
    }

    node *old_top = top;
    top = top->next;
    delete old_top;
}

void display()
{
    node *temp = new node;  // no need to allocate a node in a
                            // function that should only make output
    temp = top;             // the memory temp points to before the
                            // assignment leaks

    while (temp != NULL)
    {
        cout << temp->data << " ";
        temp = temp->next;
    }
    while (top == NULL)  // why a loop?
    {
        cout << "\nStack is Empty " << endl;
        exit (0);   // again ...
    }
}

->

void display() const
{
    if (!top) {
        std::cout << "Stack is empty!\n";
        return;
    }

    for(node *current = top; current; current = current->next)
        cout << current->data << ' ';
}
0 голосов
/ 28 сентября 2018

Нет, вывод правильный.

a.push(5);
a.display();

Отображает первые 5.

a.push(10);
a.display();

5 все еще находится в стеке, поэтому теперь отображается10 и затем 5.

a.pop();
a.pop();
a.push(20);
a.display();

Теперь все удалено, добавлено 20 и отображается, так что это должно просто отобразить 20.

И тогда пустая пачка печатается с

a.pop();
a.display();

Итак, вместе она должна отображать 5 10 5 20 Stack is Empty.

...