i have an assignment to create a circular linked list.
after adding to my list and printing it out it looks likt
"one two three four"
after using a moveFirst() method and say i wanted to start with three it should look like this
"three four one two"
However i cannot get my moveFirst() method to work properly i have tried many different ways but cannot get it to work. I understand all the concepts of how to do this it is just the actual coding to get it to do so.
public class LinkedList<T> implements ListInterface<T> { private Node<T> head, tail; private int count; public LinkedList() { count=0; head = new Node<T>(null); head.setNext(new Node<T>(null)); tail = head.getNext(); if(tail.getNext()==null) tail.setNext(head); } public void add(T elt){ tail.setData(elt); tail.setNext(new Node<T>(null)); tail=tail.getNext(); count++; } public void addFirst(T elt){ head.setNext(new Node<T>(elt, head.getNext())); count++; } public void addAt(T elt, int idx){ int i; Node<T> p=head; if (idx<0 || idx>count) throw new IllegalArgumentException("Out of bounds: " + idx); for (i=0; i<idx; i++) p = p.getNext(); p.setNext(new Node<T>(elt,p.getNext())); count++; } public int find(T elt){ Node<T> p = head.getNext(); int idx = 0; while (p!=tail) { if (p.getData().equals(elt)) return idx; p=p.getNext(); idx++; } return -1; } public boolean contains(T elt){ Node<T> p = head.getNext(); while (p!=tail) { if (p.getData().equals(elt)) return true; p=p.getNext(); } return false; } public boolean isEmpty(){ return count==0; } public void makeEmpty(){ count=0; head.setNext(tail); } public void printList(){ Node<T> p= head.getNext(); while (p!=tail) { System.out.print(p + " "); p = p.getNext(); } System.out.println(); } public T findKth(int idx){ int i; Node<T> p = head.getNext(); if (idx<0 || idx>=count) throw new IllegalArgumentException("Out of bounds: "+idx); for (i=0; i<idx; i++) p=p.getNext(); return p.getData(); } public boolean remove(T elt){ int place = find(elt); return removeAt(place); } public boolean removeAt(int idx){ Node<T> p = head; if (idx<0 || idx>=count) return false; for (int i=0; i<idx; i++) p=p.getNext(); p.setNext(p.getNext().getNext()); count--; return true; } public int size(){ return count; } public Object[] toArray(){ Node<T> p = head.getNext(); Object[] newArray = new Object[count]; int i=0; while (p!=tail) { newArray[i] = p.getData(); ++i; p=p.getNext(); } return newArray; } public void moveFirst(T newTail, T newFirst) { tail.setData(newTail); System.out.println(tail); head.setData(newFirst); System.out.println(head); } public static void main(String[] args) { LinkedList<String> ll = new LinkedList<String>(); ll.add("one"); ll.add("two"); ll.add("three"); ll.add("four"); ll.printList(); ll.moveFirst("one","three"); } }