Java implementation of double linked list data structure

First of all, double linked list is also a kind of linked list. Unlike single linked list, it not only has the pointer of the next node of the current node, but also has the pointer of the previous node of the current node, thus forming a circular linked list structure. For a double linked list, it is very convenient to add new nodes or delete a node. You only need to modify the pointer of the nodes before and after the relevant node. So for any node in the double linked list, there are three elements: the pointer of the previous node, the pointer of the next node and the object stored by the current node. Below is how java implements the double linked list structure:

public class DoubleLink<T>{
	
	private DNode mHead;//Chain header
	private int mcount;//Number of nodes
	
	private class DNode<T>{
		public DNode pre;
		public DNode next;
		public T value;
	
		public DNode(T value,DNode pre,DNode next){
			this.pre=pre;
			this.next=next;
			this.value=value;
		}
	}
	
	public DoubleLink(){
		mHead =new DNode<T>(null,null,null);
		mHead.pre=mHead.next=mHead;
		mcount=0;
	}
	
	public int getSize(){
		return mcount;
	}
	
	public boolean isEmpty(){
		return mCount==0;
	}
	
	public T get(int index){
		return getNode(index).value;
	}
	
	public T getNode(int index){
		if(index<0||index>=mCount){
			throw new IndexOutOfBoundsException();
		}
		
		if(index<=mCount/2){
			DNode<T> node =mHead.next;
			for(int i=0;i<index;i++){
				node=node.next;
			}
			return node;
		}
		
		DNode<T> rNode = mHead.pre;
		int rIndex = mCount-index-1;
		for(int j=0;j<rIndex;j++){
			rNode=rNode.pre;
		}
		
		return rNode;
	}
	
	public void insert(int index,T value){
		if(index==0){
			DNode node = new DNode<T>(value,mHead,mHead.next);
			mHead.next=node;
			node.next.pre=node;
			mCount++;
			return;
		}
		
		DNode iNode =getNode(index);
		DNode tNode = new DNode<T>(value,iNode.pre,iNode);
		iNode.pre.next=tNode;
		iNode.pre=tNode;
		mCount++;
		return;
	}
	
	public void insertFirst(T value){
		insert(0,value);
	}
	
	public void appendLast(T value){
		DNode node = new DNode<T>(value,mHead.pre,mHead);
		mHead.pre.next=node;
		mHead.pre=node;
		mcount++;
	}
	
	
	public void remove(int index){
		DNode node =getNode(index);
		node.pre.next=node.next;
		node.next.pre=node.pre;
		node=null;
		mCount--;
	}
	
	public void removeFirst(){
		remove(0);
	}
	
	public void removeLast(){
		remove(mCount-1);
	}
}

Keywords: Java

Added by fallen00sniper on Tue, 21 Apr 2020 18:56:46 +0300