下面是我写的一个栈程序代码,要求:创建一个栈,并将数组intArray[]中的数据全部写入栈,然后显示输出所有栈内元素。
程序代码如下:
class StackElement{
int data;
StackElement nextElement;
StackElement(int data){
this.data=data;
this.nextElement=null;
}
public int Value(){
return data;
}
public void setValue(int data){
this.data=data;
}
}class Stack{
StackElement top;
Stack(){
top=null;
}
public void push(int data){
if (top==null){
top=new StackElement(data);
top.nextElement=null;
}
StackElement temp=new StackElement(data);
top.nextElement=top;
top=temp;
}
public int pop(){
if (top==null){
return -1;
}
int temp=top.Value();
top=top.nextElement;
return temp;
}
public boolean isEmpty(){
return top==null;
}
}public class StackDemo{
public static void main(String[] args){
Stack q=new Stack();
int[] intArray={31, 53, 8, 21, 9, 23};
for(int i=0; i<intArray.length; i++){
q.push(intArray[i]);
}
System.out.print("the Elements of the Stack q: ");
while(!q.isEmpty()){
System.out.print(q.pop()+" ");
}
System.out.println();
}
}
输出结果如下:
the Elements of the Stack q: 23
----------------------
问题:为什么我不能输出栈内所有的元素?
程序代码如下:
class StackElement{
int data;
StackElement nextElement;
StackElement(int data){
this.data=data;
this.nextElement=null;
}
public int Value(){
return data;
}
public void setValue(int data){
this.data=data;
}
}class Stack{
StackElement top;
Stack(){
top=null;
}
public void push(int data){
if (top==null){
top=new StackElement(data);
top.nextElement=null;
}
StackElement temp=new StackElement(data);
top.nextElement=top;
top=temp;
}
public int pop(){
if (top==null){
return -1;
}
int temp=top.Value();
top=top.nextElement;
return temp;
}
public boolean isEmpty(){
return top==null;
}
}public class StackDemo{
public static void main(String[] args){
Stack q=new Stack();
int[] intArray={31, 53, 8, 21, 9, 23};
for(int i=0; i<intArray.length; i++){
q.push(intArray[i]);
}
System.out.print("the Elements of the Stack q: ");
while(!q.isEmpty()){
System.out.print(q.pop()+" ");
}
System.out.println();
}
}
输出结果如下:
the Elements of the Stack q: 23
----------------------
问题:为什么我不能输出栈内所有的元素?
不过看来自己还是没老呀你把push改一下,改成:
public void push(int data) {
if (top == null) {
top = new StackElement(data);
top.nextElement = null;
return;
}
StackElement temp = new StackElement(data);
temp.nextElement = top;
top = temp;
}
注意什么是值,什么是引用还有,建议看看java.util.Stack的实现方法
不明白为什么加上那个return;但输出结果还是跟原来一样啊。
查看了些JDK文档,里面没有找到java.util.Stack的具体实现方法。
楼上,可以明确点,指出问题所在吗?谢谢。
StackElement temp=new StackElement(data);
top.nextElement=top;//right
top=temp;
应该是
StackElement temp = new StackElement(data);
temp.nextElement = top;//wrong
top = temp;
换句话说,应该把新建的节点的next指针指向原来的那个。util包里的Stacck可以在jdk源代码里看,到sun网上找吧。一般安装jdk都带的。你在jbuilder里面跟踪进去或者find defination也可以看到
明白就好
嘿,不好意思了,先前没仔细看清楚你给的那段代码哪。