Java用链表实现栈和队列
程序员文章站
2022-04-27 15:13:25
...
用链表实现了栈的基本操作:入栈、出栈、查看栈顶数据以及判断栈是否有数据
/** * 用链表实现栈 * @author Administrator * * @param <E> */ public class MyStackLink<E> { //定义一个初始长度为0的数组来缓存数据 Node head = null; int length = 0;//结点个数 //将数据压入栈中 public void push(E e) { //创建结点 Node n = new Node(e); n.next=head; head=n; length++; } //查看栈顶的数据 public E get() { // return head == null?null:head.e; return head.e; } //出栈 public E poll() { if(head==null) { return null; } Node n=head; head = n.next; n.next=null; length--; return n.e; } //判断栈是否为空 public boolean isEmpty() { return length == 0; } private class Node { E e; Node next; public Node(E e) { this.e = e; } } }
因为代码和功能基本上差不多就在这里一起用链表实现了队列
/** * 用链表实现队列 * @author Administrator * * @param <E> */ public class Queue<E> { Node head = null; private Node last = null; int length = 0;//结点个数 //将数据放入队列中 public void push(E e) { //创建结点 Node n = new Node(e); if(head==null) { head = n; }else { last.next = n; } last = n; length++; } //查看队列的数据 public E get() { return head == null?null:head.e; } //去队列的首数据 public E poll() { if(head==null) { return null; } Node n=head; head = n.next; n.next=null; length--; return n.e; } //判断队列是否为空 public boolean isEmpty() { return length == 0; } private class Node { E e; Node next; public Node(E e) { this.e = e; } } }