数据结构之链式栈

链式栈

class Stack2 extends onelink1{
	private onelinknode top;
	public Stack2() {
		top=null;
	}
	public  boolean isempty() {
		return top==null;
	}
	public int get() {
		if(!isempty()) {
			return top.data;
		}
		else {
			return -1;
		}
	}
	public boolean push(int k) {
		onelinknode q = new onelinknode(k);
		q.next=top;
		top=q;
		return true;
	}
	public int pop() {
		int k=-1;
		if(!isempty()) {
			k=top.data;
			top=top.next;
			
		}
		return k;
	}
	
}
 






  class  onelinknode{
	   public int data;
	   public onelinknode next;
	   public onelinknode(int k) {
		   data=k;
		   next=null;
	   }
	   public onelinknode() {
		   this(0);
	   }
}

class onelink1{
	   protected onelinknode head;
	   public onelink1(onelinknode h1) {
		   head=h1;
	   }
	   public onelink1() {
		   head=null;
	   }
	   public boolean isempty() {
		   return head==null;
	   }

	   
	   public onelink1(int n) {
		   onelinknode rear,q;
		   if(n>0) {
			   int k=(int)(Math.random()*100); 
			   head = new onelinknode(k);
			   rear=head;
			   for(int i=1;i<n;i++) {
				   k=(int)(Math.random()*100);
				   q=new onelinknode(k);
				   rear.next=q;
				   rear=q;
			   }
		   }
			   
	   }

	   public int length() {
		   onelinknode p=head;
		   int i=0;
		   while(p!=null) {
			   i++;
			   p=p.next;
		   }
		   return i;
	   }
	   public void output() {
		   output(head);
	   }
	   public void output(onelinknode p) {
		   while(p!=null) {
			   System.out.print(p.data);
			   p=p.next;
			   if(p!=null)
				   System.out.print("->");
		   }
		   System.out.println();
	   }
	   public int get(int i) {
		   int j=1;
		   onelinknode p=head;
		   while(p!=null&&j<i) {
			   p=p.next;
			   j++;
		   }
		   if(j>i||p==null)
			   return 0;
		   return p.data;
	   }


	    	
	    	
	    	```

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值