我正在尝试使用 C++ 中的链表创建一个堆栈。但是我写的显示函数只打印堆栈的顶部。我真的不明白为什么会这样。非常感谢任何帮助或澄清。谢谢
#include<iostream.h>
#include<conio.h>
class Node
{
protected:
Node* next;
int data;
public:
Node(int d){data=d;}
friend class Stack;
};
class Stack
{
public:
Stack(){top->next='\0';length=0;}
void push(int d)
{
Node *n=new Node(top->data);
n->next='\0';
top->next=n;
top->data=d;
length++;
}
int pop()
{
top=top->next;
length--;
return top->data;
}
void displaystack()
{
while(top->next!='\0')
{
cout<<top->data<<endl;
top=top->next;
}
}
int getlength()
{
return length;
}
private:
Node *top;
int length;
};
void main()
{
clrscr();
Stack s;
s.push(9);
s.push(8);
s.push(7);
s.push(6);
s.push(5);
s.push(3);
s.displaystack();
int len=s.getlength();
cout<<"length of stack is "<<len<<endl;
getch();
}
它只打印以下内容: 3 堆栈的长度是 6
--------xxxxxxx--------xxxxxxxx--------xxxxxxx-----------xxxxxxxxxxxxx------------ --
编辑后的代码如下所示:并且也可以工作!(感谢@Kaathe):P
#include<iostream.h>
#include<conio.h>
class Node
{
protected:
Node* next;
int data;
public:
Node(int d){data=d;}
friend class Stack;
};
class Stack
{
public:
Stack(){top->next=NULL;length=0;}
~Stack()
{
while(top!=NULL)
{
Node* toDelete=top;
top=top->next;
delete toDelete;
}
}
void push(int d)
{
Node *n=new Node(d);
n->next=top;
top=n;
length++;
}
int pop()
{
Node* oldtop=top;
top=top->next;
int oldtopdata=oldtop->data;
delete(oldtop);
--length;
return oldtopdata;
}
void displaystack()
{
Node* current=top;
while(current->next!=NULL)
{
cout<<current->data<<endl;
current=current->next;
}
}
int getlength()
{
return length;
}
private:
Node *top;
int length;
};