JAVA 双链表

public class FirstLastList {
	private class Data{
		private Object obj;
		private Data next = null;
		
		Data(Object obj){
			this.obj = obj;
		}
	}
	
	private Data first = null;
	private Data last = null;
	
	public void insertFirst(Object obj){
		Data data = new Data(obj);
		if(first == null)
			last = data;
		data.next = first;
		first = data;
	}
	
	public void insertLast(Object obj){
		Data data = new Data(obj);
		if(first == null){
			first = data;
		}else{
			last.next = data;

		}
		last = data;
	}
	
	public Object deleteFirst() throws Exception{
  		if(first == null)
   			throw new Exception("empty");
  		Data temp = first;
  		if(first.next == null)
   			last = null;
  		first = first.next;
  		return temp.obj;
 	}	
	
	public void deleteLast() throws Exception{
		if(first == null)
			throw new Exception("empty");
		if(first.next == null){
			first = null;
			last = null;
		}else{
			Data temp = first;
			while(temp.next != null){
				if(temp.next == last){
					last = temp;
					last.next = null;
					break;
				}
				temp = temp.next;
			}
		}
	}
	
	public void display(){
		if(first == null)
			System.out.println("empty");
		Data cur = first;
		while(cur != null){
			System.out.print(cur.obj.toString() + " -> ");
			cur = cur.next;
		}
		System.out.print("\n");
	}
	
	public static void main(String[] args) throws Exception {
		FirstLastList fll = new FirstLastList();
		fll.insertFirst(2);
		fll.insertFirst(1);
		fll.display();
		fll.insertLast(3);
		fll.display();
		fll.deleteFirst();
		fll.display();
		fll.deleteLast();
		fll.display();
	}
}

  

  

转载于:https://www.cnblogs.com/liyantsc/p/4729040.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值