基于链表的栈实现


结点类

package com.java.linkStack;

public class Node {
	public  t data;
	public Node next;
	public Node(t data){
		this.data=data;
		next=null;
	}
}

package com.java.linkStack;

public class linkStack{
	private Node top;
	private int size=0;
	public linkStack() {
		top=null;
	}
	
	public void push(t data){
		Node node=new Node(data);
		size++;
		//栈内为空,则栈顶新建结点
		if(top==null) top=node;
		else{
			//新结点next指针指向旧top
			node.next=top;
			//top指向新结点
			top=node;
		}
	}
	
	public t peek(){
		if(top==null){
			throw new RuntimeException("栈为空");
		}
		return (t) top.data;
	}
	
	
	public t pop(){
		Node oldtop=top;
		if(top==null){
			throw new RuntimeException("栈为空");
		}
			size--;
			t result=(t) top.data;
			top=top.next;
			oldtop.next=null;
			return result;
		
	}
	
	public int size(){
		return size;
	}
	
	public void print(){
		Node temp=top;
		if(top==null){
			throw new RuntimeException("栈为空");
		}
		System.out.println(top.data);
		while((top=top.next)!=null){
			System.out.println(top.data);
		}
		top=temp;
		
	}
}

package com.java.linkStack;

public class Test {

	public static void main(String[] args) {
		linkStack stack=new linkStack();
		stack.push("hello");
		stack.push("world");
		stack.print();
		System.out.println(stack.size());
		System.out.println(stack.pop());
		System.out.println(stack.size());
		stack.print();

	}
	
}


你可能感兴趣的:(数据结构)