
public class LinkedList implements Cloneable{

	private Node head=null;

	public int length(){
		Node pos = head;
		int count=0;
		while(pos != null){
			++count;
			pos=pos.getNext();
		}
		return count;
	}
	
	public void print(){
		Node pos = head;
		if(pos==null){
			System.out.println("NO Nodes !!");
		}
		else{
			while(pos != null){
				System.out.println(pos.toString());
				pos=pos.getNext();
			}
		}
	}


	public void add(int pow,int coff){
		Node newNode = new Node(pow, coff);
		Node pos=head;

		if(head==null){
			newNode.setNext(head);
			head = newNode;

		}

		else{
			if(pos.getPower() < newNode.getPower()){
				newNode.setNext(head);
				head = newNode;
			}
			else{
				while(pos.getNext() != null && (pos.getNext().getPower() > newNode.getPower()))
					pos=pos.getNext();


				newNode.setNext(pos.getNext());
				pos.setNext(newNode);
			}
		}
	}

	public LinkedList sum(LinkedList list2){
		LinkedList finalList = new LinkedList();

		Node pos1 = head;
		Node pos2 = list2.getHead();

		while(pos1 != null){
			if(pos1.getPower() == pos2.getPower()){
				finalList.add(pos1.getPower(), (pos1.getCoff()+pos2.getCoff()));
				pos1 = pos1.getNext();
				pos2 = list2.getHead();

			}

			else{
				pos2 = pos2.getNext();
				if(pos2 ==null){
					finalList.add(pos1.getPower(), pos1.getCoff());
					pos2 = list2.getHead();
					pos1=pos1.getNext();
				}
			}
		}

		
		pos2 = list2.getHead();
		Node pos3 = finalList.getHead();

		int counter=0;

		while(pos2 != null){

			if(pos2.getPower() != pos3.getPower() ){
				++counter;
				pos3=pos3.getNext();

				if(pos3 == null){
					if(counter == finalList.length()){
						finalList.add(pos2.getPower(), pos2.getCoff());
						counter=0;
						pos2 = pos2.getNext();
						pos3=finalList.getHead();
					}
					else{
						counter=0;
						pos2=pos2.getNext();
						pos3=finalList.getHead();
					}
				}
			}
			else{
				pos3=pos3.getNext();

				if(pos3 == null){
					if(counter == finalList.length()){
						finalList.add(pos2.getPower(), pos2.getCoff());
						counter=0;
						pos2 = pos2.getNext();
						pos3=finalList.getHead();
					}
					else{
						counter=0;
						pos2=pos2.getNext();
						pos3=finalList.getHead();
					}
				}
			}


		}

		return finalList;
	}




	public Node getHead() {
		return head;
	}


	/*public static LinkedList clone(LinkedList finalList){
		LinkedList temp = new LinkedList();
		Node pos3 = finalList.getHead();
		while(pos3 != null){
			temp.add(pos3.getPower(), pos3.getCoff());
			pos3=pos3.getNext();
		}

		return temp;


	}

*/









}
