利用java语言实现自定义队列与栈

自定义栈实现:

public class MibuStack<T> {
// 定义小大
private int size;
// 默认数据大小为4
private Object[] array = new Object[4];
// 非空判断函数
public boolean isEmpty(){
	if (size==0) {
		return true;
	}else{
		return false;
	}
}
public int size(){
	return size;
}
// 扩容函数
public void expandCapacity(){
	Object[] newArray = new Object[size*2];
	System.arraycopy(array, 0, newArray, 0, size);
	array = newArray;
}
// 向栈内压元素
public void push(T t){
	array[size]=t;
	size++;
	if(size==array.length){
		expandCapacity();
	}
}
// 弹出栈顶元素
@SuppressWarnings("unchecked")
public T peek(){
	if (isEmpty()) {
		return null;
	}else{
		return (T) array[size-1];
	}
}
// 移除栈顶元素
public T pop(){
	if (isEmpty()) {
		return null;
	} else {
      T t = peek();
      array[size-1]=null;
      size--;
      return t;
	}
}

}
自定义队列实现:
public class MyQueue<T> {
	private int size;
	public boolean isEmpty(){
		if (size==0) {
			return true;
		}else{
			return false;
		}
	}
	public int size(){
		return size;
	}
	private ListNode<T> head;
	private ListNode<T> last;
	public MyQueue(ListNode<T> head, ListNode<T> last) {
		super();
		head = new ListNode<T>(null, null) ;
		last = head;
	}
	public void offer(T t){
		ListNode<T> node = new ListNode<T>(t, null);
		last.next=node;
		last=node;
		size++;
	}
	
	public T peek(){
		if (isEmpty()) {
			return null;
		} else {
            return head.next.value;   
		}
	}
	public T poll(){
		if (isEmpty()) {
			return null;
		} else {
          ListNode<T> p=head.next;
          head.next=p.next;
          size--;
          if (size==0) {
			last=head;
		  }
          return p.value;
		}
	}
	
	
}

class ListNode<T>{
	T value;
	ListNode<T> next;
	public ListNode(T value, ListNode<T> next) {
		super();
		this.value = value;
		this.next = next;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值