【数据结构笔记】链栈——Java实现

栈是一种线性数据结构,它像是放羽毛球的圆柱形容器,栈中的元素,栈遵循“先进后出”(First In Last Out,FILO),最早入栈的元素叫做栈底,最晚入栈的元素叫做栈顶,每次出栈的只能是栈顶元素,它可以由链表或数组实现,这里展示的是链表实现的栈——链栈。

public class LinkStack {
	private Node top;
	private int size;
	
	public class Node{
		int data;
		Node next;
		public Node(int data){
			this.data = data;
		}
	}

	//入栈
	public int push(int value){
		Node pushNode = new Node(value);
		pushNode.next = top;
		top = pushNode;
		size++;
		return top.data;
	}
	
	//出栈
	public int pop(){
		Node oldNode = top;
		top = top.next;
		size--;
		return oldNode.data;
	}
	
	//得到栈顶值不出栈
	public int peek(){
		return top.data;
	}
	//栈长
	public int length(){
		return size;
	}
	
	public static void main(String[] args) {
		LinkStack linkStack = new LinkStack();
		linkStack.push(11);
		linkStack.push(22);
		linkStack.push(33);
		linkStack.push(44);
		linkStack.push(55);
		linkStack.push(66);
		linkStack.push(77);
		
		System.out.println(linkStack.peek());
		System.out.println(linkStack.length());
		
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
		System.out.println(linkStack.pop());
	}
}

 

你可能感兴趣的:(【数据结构笔记】链栈——Java实现)