65,211
社区成员
发帖
与我相关
我的任务
分享
问题出在你的出栈函数.
把你的程序简单修改了下, 你自己看看.
#include <iostream>
#include <string>
#define STACK_SIZE 100;
using namespace std;
class student_node
{
public:
int number;string name,sex,mark;
student_node *next;
student_node(int num,string na,string s,string ma):number(num),name(na),sex(s),mark(ma){}
void print()
{
cout<<number <<"\t" <<name <<"\t" <<sex <<"\t" <<mark <<endl;
}
};
typedef struct
{
student_node**base;
int top;
int stacksize;
}sqstack;
void initstack(sqstack &s)
{
s.base=new student_node* [100];
s.top=0;
s.stacksize=0;
}
int push(sqstack&s, student_node*a)
{
if(s.stacksize >= 100)
{
cout <<"ERROR: the stack is full!" <<endl;
return -1;
}
s.stacksize++;//所有元素入栈后, top最后还要加 1, 所以s.base[s.top] == NULL!
//所以如果要出栈, 记得首先top减 1,
s.base[s.top] = a;
s.top++;
return 0;
}
int pop(sqstack&s,student_node*&a)
{
if(s.stacksize==0)
{
cout <<"ERROR: the stack is empty!" <<endl;
return -1;
}
s.stacksize--;
s.top--;//问题就出在这两句, 现在这样是正确的, 要先减 1, 否则s.base[s.top] == NULL
//也就会出现你说的错误了.
a = s.base[s.top];
return 0;
}
int stackempty(sqstack s)
{
if(s.stacksize > 100)
return 0;
else
return -1;
}
void reverse_list(student_node*& a)
{
student_node *tmp = NULL;
student_node *tmp2 = a;
sqstack s;
initstack(s);
while(tmp2 != NULL)
{
push(s,tmp2);
tmp2 = tmp2->next;
}
cout <<s.stacksize <<endl;
cout <<"111111" <<endl;
pop(s,a);//如果出栈函数不先减 1 的话, 第一次pop 得到的a 就是NULL
tmp = a;
cout <<"222222" <<endl;
cout <<s.stacksize <<endl;
while(s.stacksize!=0)
{
pop(s,tmp2);
cout <<"333333" <<endl;
tmp->next=tmp2;//那么这里也就会出错了
cout <<"444444" <<endl;
tmp=tmp->next;
}
tmp->next=NULL;
}
void create_list(student_node *&a)
{
int n;int num;string s,ma,na;
cout <<"how many students?" <<endl;
cin>>n;
cout <<"for the first student's information" <<endl;
cin>>num>>na>>s>>ma;
a=new student_node(num,na,s,ma);
student_node *p;
student_node *t=a;
for(int i = 2; i <= n; i++)
{
cout <<"for the next student's information" <<endl;
cin>>num>>na>>s>>ma;
p=new student_node(num,na,s,ma);
t->next=p;t=p;
}
t->next=NULL;
}
void print_list(student_node *a)
{
while(a!=NULL)
{
a->print();
a=a->next;
}
}
int main()
{
student_node*head=NULL;
create_list(head);
print_list(head);
reverse_list(head);
print_list(head);
return 0;
}