
public class Cursor<T> {


	private Node<T>[] cursorList;

	public Cursor(int size) {


		cursorList = new Node[size];

		for (int i = 0; i < cursorList.length; i++) {
			cursorList[i]= new Node<>();
		}

		for (int i = 0; i < cursorList.length; i++) {
			if(i==cursorList.length-1)
				cursorList[i].setNext(0);
			else
				cursorList[i].setNext(i+1);

		}
	}

	public void print(){
		for (int i = 0; i < cursorList.length; i++) {
			System.out.println(i+"   "+cursorList[i].toString());
		}
	}


	public int creatList(){
		if(cursorList[0].getNext()==0){
			return -1;
		}
		else{
			Node<T> head =new Node<>();
			int temp=cursorList[0].getNext();
			cursorList[0].setNext(cursorList[temp].getNext());
			cursorList[temp]=head;
			return temp;
		}
	}

	public boolean add(int head,T data){
		if(cursorList[0].getNext()==0){
			return false;
		}

		Node<T> newNode = new Node<>(data);

		int temp = cursorList[0].getNext();
		cursorList[0].setNext(cursorList[temp].getNext());
		cursorList[temp]=newNode;

		if(cursorList[head].getNext()==0){
			cursorList[head].setNext(temp);
			return true;
		}

		int pos = cursorList[head].getNext();


		while(cursorList[pos].getNext()!=0){

			pos=cursorList[pos].getNext();
		}
		cursorList[pos].setNext(temp);


		return true;	
	}

	public boolean delete(int head,T data){
		if(cursorList[head].getNext()==0){
			return false;
		}

		int temp = find(head, data);
		if(temp==0)
			return false;

		int pos = findPrev(head, temp);



		int index=cursorList[0].getNext();
		cursorList[0].setNext(cursorList[pos].getNext());
		cursorList[pos].setNext(cursorList[temp].getNext());
		cursorList[temp].setNext(index);
		return true;



	}

	public int find(int head,T data){

		int pos=cursorList[head].getNext();

		while(pos!=0 && cursorList[pos].getData() != data){
			pos=cursorList[pos].getNext();
		}
		return pos;

	}



	public boolean isLast(int pos){
		return (cursorList[pos].getNext()==0);
	}

	public int findPrev(int head,int temp){
		int pos = cursorList[head].getNext();

		if(cursorList[cursorList[head].getNext()].getData() == cursorList[temp].getData())
			return head;

		while(cursorList[cursorList[pos].getNext()].getData() != cursorList[temp].getData() && cursorList[cursorList[pos].getNext()].getNext()!=0 )
			pos=cursorList[pos].getNext();

		return pos;
	}


	public void swap(int head,T data1,T data2){

		int indexD1 = find(head, data1);
		int indexD2 = find(head, data2);
		
		if(indexD1==0 || indexD2==0)
			return;
		
		int next1= cursorList[indexD1].getNext();
		int next2 = cursorList[indexD2].getNext();

		int prev1 = findPrev(head, indexD1);
		int prev2 = findPrev(head, indexD2);


		cursorList[prev1].setNext(indexD2);
		cursorList[prev2].setNext(indexD1);

		if(next2 != indexD1)
			cursorList[indexD1].setNext(next2);
		else
			cursorList[indexD1].setNext(indexD2);

		
		if(next1 != indexD2)
			cursorList[indexD2].setNext(next1);
		else
			cursorList[indexD2].setNext(indexD1);

	}





















}
