链栈的基本操作-java实现

package ldm;
import java.util.*;
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;
	}
}
class linkStack<T>{
	private Node<T> top;
	private int length;
	public linkStack() {
		length=0;
		top=null;
	}
	public void push(T obj) {
		top=new Node<T>(obj,top);
		length++;
	}
	public T pop() {
		if(top==null) {
			System.out.println("栈已空,无法删除元素!");
			return null;
		}
		T x=top.data;
		top=top.next;
		length--;
		return x;
	}
	public T getHead(){
		if(top==null) {
			System.out.println("栈已空,无法读取元素!");
			return null;
		}
		return top.data;
	}
	public boolean isEmpty() {
		return top==null;
	}
	public int size() {
		return length;
	}
	public void nextOrder() {
		Node<T>p=top;
		while(p!=null) {
			System.out.println(p.data);
			p=p.next;
		}
	}
	public void clear() {
		top=null;
	}
}
public class Main {
	public static void main(String[] argc) {
		linkStack<Integer>L=new linkStack<Integer>();
		int a[]= {23,56,12,49,35};
		for(int i=0;i<a.length;i++) L.push(a[i]);
		System.out.println("栈中的数据元素为: ");
		L.nextOrder();
		L.push(9999999);
		System.out.println("执行插入操作后的栈中的数据元素为: ");
		L.nextOrder();
		L.pop();
		System.out.println("执行删除操作后的栈中的数据元素为: ");
	    L.nextOrder();
	}
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值