проблема кругового связанного списка в Java - PullRequest
0 голосов
/ 03 апреля 2011

Привет, у меня проблемы с моим классом кругового связного списка. я предполагаю иметь круговой связанный класс, который проходит через элементы заданного количества. когда он достигает конца списка, он перемещается обратно к началу списка и начинается как цикл вокруг себя. Ну, моя проблема в том, что я не могу заставить свой список зацикливаться на методах, которые я сделал. Предполагается, что у меня есть метод, который добавляет элементы в конец списка, и метод, который устанавливает их в начало списка. Ну, мой задний фронт не работает правильно, поэтому я подумал, что я отправлю и посмотрим, поможет ли какой-нибудь код. Кроме того, я хочу запустить цикл со строками, как я хочу создать круговой связанный список, который проходит по дням недели, начиная с воскресенья и заканчивая субботой, затем связывая субботу с воскресеньем и выполняя цикл по всему agian. Может ли кто-нибудь показать мне, как сделать это при тестировании моего кода.

мой вывод выходит как

Следует напечатать 1 2 3 4 1 2 3 4 1 2 3
1 2 3 4 1 2 3 4 1 2 3
Следует напечатать 3 4 1 2 3 4 1 2 3 4 1
3 1 2 3 4 1 2 3 4 1 2
Следует напечатать 3 4 1 2 -1 3 4 1 2 -1 3
3 1 2 3 4 -1 3 1 2 3 4
Должно быть напечатано 3 1 2 -1 3 1 2 -1 3 1 2
3 1 2 3 -1 3 1 2 3 -1 3

Код:

public class LinkedListIterator<T> implements Iterator<T> {
private PublicNode<T>first;
private PublicNode<T>current;

    public LinkedListIterator(PublicNode<T> first){
        this.first =first;
        current = first;
    }
    public boolean hasNext() {
        return current!=null;
    }
    public T next() {
        if(!hasNext()){
            throw new NoSuchElementException();
        }
        T result = current.getElement();
        current = current.getNext();
        return result;
    }

    public void remove() throws UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }
    public void setFirst(PublicNode<T> first) {
        this.first = first;
    }
    public PublicNode<T> getFirst() {
        return first;
    }

}

И

public class CircularLinkedList<T> implements CircularList<T> {
    private PublicNode<T> head;
    private PublicNode<T> tail;
    private int size;


    public CircularLinkedList() {
        head = null;
        tail = null;
        size = 0;
    }
    //bigO(1)
    public PublicNode<T> getHead() {
        return head;
    }
    //bigO(1)
    public void setHead(PublicNode<T> head) {
        this.head = head;
    }
    //bigO(1)
    public PublicNode<T> getTail() {
        return tail;
    }
    //bigO(1)
    public void setTail(PublicNode<T> tail) {
        this.tail = tail;
    }
    //bigO(1)
    public int getSize() {
        return size;
    }
    //bigO(1)
    public void setSize(int count) {
        this.size = count;
    }
    //bigO(1)
    public boolean isEmpty() {
        return tail == null || head == null;
    }

    // add element to the end of the list
    public void addLast(T element) {
        PublicNode<T> node = new PublicNode<T>(element);
        if(this.tail==null){
            node.setNext(null);
            node.setPrevious(null);
            this.tail=node;
        }else{
            PublicNode<T> oldTail = this.tail;
            oldTail.setNext(node);
            node.setNext(head);
            node.setPrevious(oldTail);
            this.tail =node;
        }if(this.head==null){
            this.head=node;
        }
        this.size++;
    }

            // set element to be front of the list
    //bigO(n)
    public void setFront(T element) {
        PublicNode<T> node = new PublicNode<T>(element);
        if (isEmpty()) {
            throw new NoSuchElementException();
        }else{
            PublicNode<T> oldHead = this.head;
            oldHead.setPrevious(node);
            node.setNext(oldHead);
            node.setPrevious(null);
            this.head=node;
        }
        if(this.tail==null){
            this.tail=node;
        }
        this.size++;

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CircularList<Integer> list = new CircularLinkedList<Integer>();
        for (int i = 1; i <= 4; i++) {
            list.addLast(i);
        }

        System.out.println("\nShould print 1 2 3 4 1 2 3 4 1 2 3");
        Iterator<Integer> iter = list.iterator();
        for (int i = 1; iter.hasNext() && i <= 11; i++) {
            System.out.print(" " + iter.next());
        }
        System.out.println();

        list.setFront(3);

        System.out.println("Should print 3 4 1 2 3 4 1 2 3 4 1");
        iter = list.iterator();
        for (int i = 1; iter.hasNext() && i <= 11; i++) {
            System.out.print(" " + iter.next());
        }
        System.out.println();

        list.addLast(-1);

        System.out.println("Should print 3 4 1 2 -1 3 4 1 2 -1 3");
        iter = list.iterator();
        for (int i = 1; iter.hasNext() && i <= 11; i++) {
            System.out.print(" " + iter.next());
        }
        System.out.println();

        list.remove(4);

        System.out.println("Should print 3 1 2 -1 3 1 2 -1 3 1 2");
        iter = list.iterator();
        for (int i = 1; iter.hasNext() && i <= 11; i++) {
            System.out.print(" " + iter.next());
        }
    }

}

Ответы [ 2 ]

0 голосов
/ 03 апреля 2011

В CircularLinkedList<T>.setFront(T) вы создаете новый узел и добавляете его в начало кругового списка, а не находите узел с заданным значением и изменяете CircularLinkedList<T>.head для ссылки на найденный узел.

0 голосов
/ 03 апреля 2011

попробуйте что-то подобное в else из setFront()

PublicNode<T> node = head.next();
PublicNode<T> nodeToBeFound;
while(node!=head){
    is(node.element() == element)
        nodeToBeFound = node;
    node = node.next();
}
head = nodeToBeFound;
tail = head.previous();
...