Java uses a linked list (with virtual head node) to implement the stack

Java uses a linked list (with virtual head node) to implement the stack


Interface Stack<E>

/**
 * @author yinglongwu
 */
public interface Stack<E> {

	int getSize();
	boolean isEmpty();
	void push(E e);//入栈
	E pop();//出栈
	E peek();//查看栈顶元素
}


Implement the interface

Here is achieved through the interface from the list Stack class definition in the method, thus the formation of the LinkedListStack class
custom LinkedList class: point I jump https://blog.csdn.net/qq_43594119/article/details/105331407

package pers.ylw.stack;

/**
 * @author yinglongwu
 */
//使用链表实现栈
public class LinkedListStack<E> implements Stack<E> {

	private LinkedList<E> list; //自定义的LinkedList类:https://blog.csdn.net/qq_43594119/article/details/105331407
	
	public LinkedListStack() {
		list = new LinkedList<>();
	}

	@Override
	public int getSize() {
		return list.getSize();
	}

	@Override
	public boolean isEmpty() {
		return list.isEmpty();
	}

	//入栈
	@Override
	public void push(E e) {
		list.addFirst(e);
	}

	//出栈
	@Override
	public E pop() {
		return list.removeFirst();
	}

	//查看栈顶元素
	@Override
	public E peek() {
		return list.getFirst();
	}
	
	//重写toString方法,便于输出信息
	@Override
	public String toString() {
		StringBuilder res = new StringBuilder();
		res.append("Stack: top ");
		res.append(list);
		return res.toString();
	}
	
	public static void main(String[] args) {
		
		//测试
		LinkedListStack<Integer> stack = new LinkedListStack<Integer>();
		
		//包装类和其对应的基本数据类型可以自动转换
		//将0到4入栈
		for (int i = 0; i < 5; i++) {
			stack.push(i);
			System.out.println(stack);
		}
		
		//出一次栈
		stack.pop();
		System.out.println(stack);
	}
}

Output result
Insert picture description here

Published 318 original articles · Like 44 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/qq_43594119/article/details/105333193
Recommended