数据结构-第二篇:链栈

/**

  • 链栈:
  • 采用链式存储结构实现
  • 技巧:
  • 栈顶指针指向链表的第一个节点
  • 时间复杂度:
  • 插入:O(1)
  • 删除:O(1)
  • @author hopefully

*/

public class LinkStack<T> {

	private Node<T> top;
	private int length;

	public LinkStack() {
		top=null;
	}
	
	//is empty?
	public boolean isEmpty() {
		return top==null;
	}
	
	//push
	public void push(T obj) {
		/*Node<T> p=new Node<>(obj,null);
		p.next=top;
		top=p;
		*/
		top=new Node<T>(obj,top);
		length++;
	}
	
	//出栈
	public T pop() {
		if(isEmpty()) {
			System.out.println("栈空");
			return null;
		}
		T res=top.data;
		top=top.next;
		length--;
		return res;
	}
	
	//peek
	public T peek() {
		if(isEmpty()) {
			System.out.println("栈空");
			return null;
		}
		return top.data;
	}
	
	//遍历
	public void traverse() {
		Node<T> p=top;
		while(p!=null) {
			System.out.print(p.data+" ");
			p=p.next;
		}
		System.out.println();
	}
	
	//栈长
	public int size() {
		return length;
	}
	
	//销毁
	public void destroy() {
		top=null;
	}
	
	public static void main(String[] args) {
		LinkStack<Integer> linkStack=new LinkStack<Integer>();
		for(int i=1;i<=20;i++) {
			linkStack.push(i);
		}
		linkStack.traverse();
		System.out.println(linkStack.pop());
		System.out.println(linkStack.peek());
		System.out.println(linkStack.size());
	}
}
class Node<T>{
	T data;
	Node<T> next;
	
	public Node(Node<T> n) {
		next=n;
	}
	
	public Node(T obj, Node<T> n) {
		data=obj;
		next=n;
	}
	
	public T getData() {
		return data;
	}
	
	public Node<T> getNext(){
		return next;
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值