java链表自定义一个栈_java自定义栈(链表实现)

使用链表来实现栈比用数组更加方便,也易于节省空间,因为栈只能在栈顶进行操作,不需要进行随机访问栈元素

首先实现栈接口IStack,提供出栈、入栈、获取栈顶元素、判断是否为空以及清空栈等基本功能:

定义一个Node类,用于保存链中点的信息:

package my.stack;

public class Node {

private T data;

private Node next;

public Node(){

data = null;

next = null;

}

public Node(T data){

this.data = data;

this.next = null;

}

public Node(T data, Node next){

this.data = data;

this.next = next;

}

public void setData(T data){

this.data = data;

}

public T getData(){

return this.data;

}

public void setNext(Node next){

this.next = next;

}

public Node getNext(){

return this.next;

}

}

然后再实现该IStack接口;

package my.stack;

public class LinkedStack implements IStack {

private Node top;

private int size;

public LinkedStack(){

this.top = null;

this.size = 0;

}

public LinkedStack(T data){

this();

Node node = new Node(data);

this.top = node;

this.size ++;

}

@Override

public void clear() {

this.top = null;

this.size = 0;

}

@Override

public boolean isEmpty() {

return this.top == null;

}

@Override

public T peek() {

return this.top.getData();

}

@Override

public T pop() {

Node oldTop = this.top;

if(top == null){

return null;

}

this.top = this.top.getNext();

this.size --;

return oldTop.getData();

}

@Override

public void push(T element) {

Node node = new Node(element,top);

this.top = node;

this.size ++;

}

public int size(){

return this.size;

}

}

编写一个基本客户端用来测试功能是否满足,是否有明显的错误;

package my.stack;

public class MyArrayStackClient {

public static void main(String[] args) {

ArrayStack stack = new ArrayStack();

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

stack.push(5);

System.out.println(stack.isEmpty());

System.out.println(stack.peek());

//System.out.println(stack.pop());

System.out.println(stack.size());

stack.clear();

System.out.println(stack.size());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值