0
#include <bits/stdc++.h>
using namespace std;
struct node {
     string s;
     node* link;
}*top=NULL,*temp,*p;

node* new_node(node a){
     p=new node;
     p->s=a.s;
     p->link=a.link;
     top=p;
}
void showstack(){
     *temp=*top;
     while(temp!=NULL){
          cout<<top->s;
          temp=top->link;
     }
}
int main(){
     char a;
     int m;
     int i=0;
     node push;
     do{  std::cin >> push.s;
          if(top==NULL)
               push.link=NULL;
          else
               push.link=top;
          new_node(push);
          i++;
     }while(i<=5);
     cout<<top->s;
     showstack();
     return 0;
}

i wrote the above code trying to implement a linked stack in c++ however after giving the input the program is hanging and no response.why is it so? i checked and rechecked many times and found no bug.pls help!!

  • Please apply **C**apitalization rules where appropriate, indent your code and [clarify](https://stackoverflow.com/posts/48344001/edit) what the question is. Before you do, please take [the tour](https://stackoverflow.com/tour) and read [the help page](https://stackoverflow.com/help). Welcome to SO. – Ron Jan 19 '18 at 15:07
  • 2
    `temp=top->link;` Here, `top->link` never changes, so `temp` never changes, so loop never ends. – 001 Jan 19 '18 at 15:09
  • 2
    Run the program in a debugger and when it hangs pause the program and check where it is hanging. – nwp Jan 19 '18 at 15:09
  • thanks! but could you please give some links or reference as to where capitalisation must be there? also if possible could u also suggest how i could improve the indentation of the code. @Ron – Varun Krishna Jan 19 '18 at 15:11
  • ***i checked and rechecked many times and found no bug*** This is why you need to debug your code in an ide with a debugger like Visual Studio. Single step through the code looking at the variables at each step. – drescherjm Jan 19 '18 at 15:11
  • 1
    @nwp give a man a bug fix, and he'll eat for a day... give a man a debugger, and he can catch his own bugs? – UKMonkey Jan 19 '18 at 15:12
  • Don't use `#include `. Ever. – Christian Hackl Jan 19 '18 at 15:17
  • does it have any other disadvantage other than its compilation time?? @ChristianHackl – Varun Krishna Jan 19 '18 at 15:19
  • @VarunKrishna you might want to read this https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – UKMonkey Jan 19 '18 at 15:26
  • @VarunKrishna: All disadvantages which "Lightness Races in Orbit" lists in the excellent answer to the question linked by UKMonkey. – Christian Hackl Jan 19 '18 at 16:00

1 Answers1

2

Replace

*temp = *top;

with

temp = top;

Think about where temp points and draw boxes and arrows on some paper to understand why.

(And don't use global variables when local variables will do. It's just asking for trouble.)

molbdnilo
  • 64,751
  • 3
  • 43
  • 82