【算法系列-3】链表

双向链表

节点类:

public class DLinkNode {
	public int id;
	public String name;
	public DLinkNode next;
	public DLinkNode prev;
	
	public DLinkNode(int id, String name){
		this.id = id;
		this.name = name;
	}
	
	public void display(){
		System.out.println("id-->" + id + ", name-->" + name);
	}

}

主类:

public class DLinkList {
	private DLinkNode first;
	private DLinkNode last;
	
	public boolean isEmpty(){
		if(null == first)
			return true;
		return false;
	}
	
	public void insertFirst(int id, String name){
		DLinkNode dLinkNode = new DLinkNode(id, name);
		if(isEmpty()){
			last = dLinkNode;
		}else{
			first.prev = dLinkNode;
		}
		
		dLinkNode.next = first;
		first = dLinkNode;
	}
	public void insertLast(int id, String name){
		DLinkNode dLinkNode = new DLinkNode(id, name);
		if(isEmpty()){
			first = dLinkNode;
		}else{
			last.next = dLinkNode;
			dLinkNode.prev = last;
		}
		last = dLinkNode;
	}
	public void delFirst(){
		if(isEmpty())
			return;
		if(first == last){
			first = null;
			last = null;
		}else{
			first = first.next;
			first.next.prev = null;
		}
	}
	public void delLast(){
		if(isEmpty())
			return;
		if(first == last){
			first = null;
			last = null;
		}else{
			last = last.prev;
			last.next = null;
		}
	}
	public boolean delete(int id){
		if(isEmpty()){
			System.out.println("DLinkNode is null!");
			return false;
		}

		DLinkNode current = first;
		while(null != current){
			if(current.id == id){
				if(first == last){
					first = null;
					last = null;
				}
				
				if(current == first){
					first = first.next;
				}else if(current == last){
					last = current.prev;
					current.prev.next = null;
				}else{
					current.prev.next = current.next;
					current.next.prev = current.prev;
					
				}
				
				return true;
			}

			current = current.next;
		}
			
		return false;
	}
	
	public void display(){
		DLinkNode current = first;
		if(isEmpty()){
			System.out.println("DLinkList is empty!!");
			return;
		}
		if(first == last){
			first.display();
			return;
		}
		while(null != current){
			current.display();
			current = current.next;
		}
	}
	
	public static void main(String[] args){
		DLinkList dl = new DLinkList();
		dl.insertFirst(1, "ZhangSan");
		dl.insertLast(2, "LiSi");
		dl.insertLast(3, "WangWu");
		
//		dl.delete(2);
//		dl.delFirst();
		dl.delLast();
		dl.display();
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值