小菜鸟求教Java stack的实现问题
目前刚开始看书,有点地方不太会,就是我在尝试用node实现stack,老是有问题,感觉可能是类型的问题,但是又不知道该怎么改。。。代码如下publicclasssolut...
目前刚开始看书,有点地方不太会,就是我在尝试用node实现stack,老是有问题,感觉可能是类型的问题,但是又不知道该怎么改。。。代码如下
public class solution0301 {
static class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
static class stack{
Node top;
Object pop(){
if(top!=null){
Object topdata = top.data;
top = top.next;
return topdata;
}
return null;
}
void push(Object topdata){
Node t = new Node((Integer) topdata);
t.next = top;
top = t;
}
Object peek(){
return top.data;
}
}
public static void main(String[] args){
Node n1 = new Node(12);
Node n2 = new Node(23);
Node n3 = new Node(34);
stack stack = new stack();
stack.push(n1);
stack.push(n2);
stack.push(n3);
while(stack.peek()!=null){
System.out.println(stack.pop());
}
} 展开
public class solution0301 {
static class Node{
int data;
Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
static class stack{
Node top;
Object pop(){
if(top!=null){
Object topdata = top.data;
top = top.next;
return topdata;
}
return null;
}
void push(Object topdata){
Node t = new Node((Integer) topdata);
t.next = top;
top = t;
}
Object peek(){
return top.data;
}
}
public static void main(String[] args){
Node n1 = new Node(12);
Node n2 = new Node(23);
Node n3 = new Node(34);
stack stack = new stack();
stack.push(n1);
stack.push(n2);
stack.push(n3);
while(stack.peek()!=null){
System.out.println(stack.pop());
}
} 展开
2个回答
展开全部
stack类修改一下就行了,修改处见注释
static class stack
{
Node top;
Object pop()
{
if (top != null)
{
Object topdata = top.data;
top = top.next;
return topdata;
}
return null;
}
void push(Object topdata)
{
//Node t = new Node((Integer) topdata);你push的是node,这边当int处理,自然错了
Node t = (Node)topdata;
t.next = top;
top = t;
}
Object peek()
{
if (top != null)
{
return top.data;
}
//这边再加个判断,不过对于运行期异常,不处理也是可以的
else
{
return null;
}
}
}
展开全部
public class solution0301 {
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
static class stack {
Node top;
Object pop() {
if (top != null) {
Object topdata = top.data;
top = top.next;
return topdata;
}
return null;
}
void push(Node topdata) {
Node t = new Node(topdata.data);
t.next = top;
top = t;
}
Object peek() {
return top;
}
}
public static void main(String[] args) {
Node n1 = new Node(12);
Node n2 = new Node(23);
Node n3 = new Node(34);
stack stack = new stack();
stack.push(n1);
stack.push(n2);
stack.push(n3);
while (stack.peek() != null) {
System.out.println(stack.pop());
}
}
}
追问
非常感谢,你们俩方法都对,他回复早了点就把分给他了,还是谢谢你啦!!
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询