Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Центр помощи > [Java] Сортировка списка


Автор: KatrinIceLand 16.10.2006, 16:56
Написать функцию reverse. Эта Функция новая в классе LList. Функция должна поменять местами слова на листе (в списке), первое слово становится последним, второе становится предпоследним и так далее. Это должно быть сделано путем изменения referances слов на листе (в списке), но мы не должны копировать слова на листе (в списке). 
Так же написать a main function которая – делает an instance of the class – добавляет новые слова на лист (в список) – displays лист – сортирует лист используя функцию reverse - displays сортированный лист.

Автор: LSD 16.10.2006, 17:51
Цитата(KatrinIceLand @  16.10.2006,  17:56 Найти цитируемый пост)
Это должно быть сделано путем изменения referances слов на листе (в списке), но мы не должны копировать слова на листе (в списке). 

А поподробней можно объяснить, а то нифига не понял. И заодно что за класс LList.

Автор: KatrinIceLand 16.10.2006, 18:08
Все дело в том что я сама не совсем поняла что за программу я должна написать..  smile 
Должен быть класс (Список) или LList.  Функция reverse, дожна поменять местами слова (после их введения в список)первое слово становится последним, второе становится предпоследним и так далее. 
Так же в main функции:  добавляем новые слова на лист (в список) – displays (выводим на экран) лист – сортирует лист используя функцию reverse - displays (выводим на экран) сортированный лист.
Что то примерно такое должно получиться  smile 

Автор: KatrinIceLand 16.10.2006, 19:52
Помогите хоть что-нибудь написать.  smile 
Сегодня сдавать...

Автор: LSD 16.10.2006, 20:12
Т.е. как я понял мы должны реализовать двусвязный список с возможностью инвертирования, да?

Добавлено @ 20:14 
Цитата(KatrinIceLand @  16.10.2006,  20:52 Найти цитируемый пост)
Сегодня сдавать...

Это сколько еще времени?

Автор: KatrinIceLand 16.10.2006, 21:39
Еще 5,5 часов. До полуночи я должна скинуть на web-side of my university.. (здесь сейчас 18.38)
Совсем не было времени изучить эти главы, вот сейчас сижу занимаюсь, но не уверена что останется время написать самостоятельно программу. Время как всегда не хватает  smile

Цитата

Т.е. как я понял мы должны реализовать двусвязный список с возможностью инвертирования, да?

вот как по-русски все это называется я не знаю. По-английски sorting list.. Data strustures предмет называется..

Автор: LSD 16.10.2006, 21:50
Цитата(KatrinIceLand @  16.10.2006,  22:39 Найти цитируемый пост)
По-английски sorting list.. Data strustures предмет называется..

sorting? smile Можешь выложить точное задание на английском?

Автор: KatrinIceLand 16.10.2006, 21:54
Цитата

Write the function reverse. The function is a new function in the class LList. The function shall reverse the order in the list, the first item becomes the last item, the second item becomes the second last item and so on. This shall be done by changing the referances of the items in the list, but you must not copy the items in the list. Also write a main function which – makes an instance of the class – adds some new items in the list – displays the list – reverses the list by using our function – displays the reversed list.

вот задание на английском, но мой преподаватель переводит его с исландского и я сказала бы что не самый его удачный перевод  smile 
Может вам будет лучше понятно.

Автор: LSD 16.10.2006, 21:59
Но тут нет ни слова о сортировке?

А в остальном я задание понял. Еще вопрос надо ли полностью реализовывать интерфейс java.util.List?

Автор: KatrinIceLand 16.10.2006, 22:05
Наверное надо. Похоже я безнадежно отстала. Сортировка только при том, что во всех наших главах мы изучаем сортировку.. А это задание должно быть из этих глав. Не очень поняла задание, потому что не доучила еще. Если есть возможность помочь, буду очень рада  smile 

Автор: LSD 17.10.2006, 00:28
Полностью реализовать интерфейс java.util.List я не успеваю. Не реализованные методы будут выбрасывать исключение UnsupportedOperationException, если надо могу их потом реализовать.
Но базовое условие задачи я сделал.
Код
import java.util.*;

public class ReversingList<E> implements List<E>
{
  private Entry<E> head;
  private int size = 0;

  public ReversingList()
  {
  }

  public static void main(String[] args)
  {
    ReversingList<String> list = new ReversingList<String>();
    list.add("A");
    list.add("B");
    list.add(1, "C");
    list.add(list.size(), "D");
    list.add(list.size(), "A");
    System.out.println("list.size() = " + list.size());

    printCollection(list);

    System.out.println("list.indexOf(\"A\") = " + list.indexOf("A"));
    System.out.println("list.indexOf(\"B\") = " + list.indexOf("B"));
    System.out.println("list.indexOf(\"C\") = " + list.indexOf("C"));
    System.out.println("list.indexOf(\"D\") = " + list.indexOf("D"));
    System.out.println("list.indexOf(\"E\") = " + list.indexOf("E"));
    System.out.println("list.lastIndexOf(\"A\") = " + list.lastIndexOf("A"));

    list.reverse();
    printCollection(list);
  }

  private static void printCollection(List list)
  {
    System.out.print("[");
    for(Object aList : list)
      System.out.print(aList + " ");
    System.out.println("]");
  }

  private void checkBounds(int index)
  {
    if(index < 0 || index >= size)
      throw new IndexOutOfBoundsException("Invalid index: " + index);
  }

  public void reverse()
  {
    if(head == null)
      return;

    Entry<E> h = head;
    Entry<E> t = head;
    while(t.next != null)
      t = t.next;

    while(h != t)
    {
      E e = h.element;
      h.element = t.element;
      t.element = e;
      if(h.next == t)
        break;
      h = h.next;
      t = t.previous;
    }
  }

  public int size()
  {
    return size;
  }

  public boolean isEmpty()
  {
    return size() == 0;
  }

  public boolean add(E e)
  {
    add(0, e);
    return true;
  }

  public void add(int index, E element)
  {
    if(index > size || index < 0)
      throw new IndexOutOfBoundsException("Invalid index: " + index);

    if(index == 0)
    {
      Entry<E> newEntry = new Entry<E>(element, head, null);
      if(head != null)
        head.previous = newEntry;
      head = newEntry;
    }
    else
    {
      int i = 0;
      Entry<E> current = head;
      while(i < index && current.next != null)
      {
        current = current.next;
        i++;
      }

      if(i == index)
      {
        Entry<E> newEntry = new Entry<E>(element, current, current.previous);
        if(newEntry.next != null)
          newEntry.next.previous = newEntry;
        if(newEntry.previous != null)
          newEntry.previous.next = newEntry;
      }
      else
      {
        Entry<E> newEntry = new Entry<E>(element, null, current);
        if(newEntry.previous != null)
          newEntry.previous.next = newEntry;
      }
    }
    size++;
  }

  public E get(int index)
  {
    checkBounds(index);

    int i = 0;
    Entry<E> current = head;
    while(i < index)
    {
      current = current.next;
      i++;
    }
    return current.element;
  }

  public E set(int index, E element)
  {
    checkBounds(index);

    int i = 0;
    Entry<E> current = head;
    while(i < index)
    {
      current = current.next;
      i++;
    }

    E old = current.element;
    current.element = element;
    return old;
  }


  public E remove(int index)
  {
    checkBounds(index);

    int i = 0;
    Entry<E> entry = head;
    while(i < index)
    {
      entry = entry.next;
      i++;
    }

    if(entry.previous != null)
      entry.previous.next = entry.next;
    if(entry.next != null)
      entry.next.previous = entry.previous;
    if(index == 0)
      head = entry.next;

    size--;
    return entry.element;
  }

  public boolean remove(Object o)
  {
    int index;
    boolean removed = false;
    while((index = indexOf(o)) != -1)
    {
      remove(index);
      removed = true;
    }
    return removed;
  }

  public void clear()
  {
    head = null;
    size = 0;
  }

  public int indexOf(Object o)
  {
    int i = 0;
    Entry<E> entry = head;
    while(entry != null)
    {
      if(entry.element != null)
      {
        if(entry.element.equals(o))
          return i;
      }
      else
      {
        if(o == null)
          return i;
      }
      entry = entry.next;
      i++;
    }
    return -1;
  }

  public int lastIndexOf(Object o)
  {
    int current = 0;
    int last = -1;

    Entry<E> entry = head;
    while(entry != null)
    {
      if(entry.element != null)
      {
        if(entry.element.equals(o))
          last = current;
      }
      else
      {
        if(o == null)
          last = current;
      }
      entry = entry.next;
      current++;
    }

    return last;
  }

  public boolean contains(Object o)
  {
    return indexOf(o) != -1;
  }

  public boolean containsAll(Collection<?> c)
  {
    for(Object o : c)
    {
      if(!contains(o))
        return false;
    }
    return true;
  }

  public boolean addAll(int index, Collection<? extends E> c)
  {
    for(E aC : c)
    {
      add(index, aC);
      index++;
    }
    return c.size() > 0;
  }

  public boolean addAll(Collection<? extends E> c)
  {
    return addAll(0, c);
  }

  public boolean removeAll(Collection<?> c)
  {
    for(Object o : c)
      remove(o);
    return c.size() > 0;
  }

  //////////////////// NOT IMPLEMENTED METHODS ////////////////////

  public Iterator<E> iterator()
  {
    return listIterator();
  }

  public Object[] toArray()
  {
    throw new UnsupportedOperationException();
  }

  public <T> T[] toArray(T[] a)
  {
    throw new UnsupportedOperationException();
  }

  public boolean retainAll(Collection<?> c)
  {
    throw new UnsupportedOperationException();
  }

  public ListIterator<E> listIterator()
  {
    throw new UnsupportedOperationException();
  }

  public ListIterator<E> listIterator(int index)
  {
    throw new UnsupportedOperationException();
  }

  public List<E> subList(int fromIndex, int toIndex)
  {
    throw new UnsupportedOperationException();
  }

  private static class Entry<E>
  {
    public E element;
    public Entry<E> next;
    public Entry<E> previous;

    public Entry(E element, Entry<E> next, Entry<E> previous)
    {
      this.element = element;
      this.next = next;
      this.previous = previous;
    }

    @Override
    public String toString()
    {
      return "Element[" + element + "]" +
          "(next = " + (next == null ? "null" : next.element) +
          " , previous = " + (previous == null ? "null" : previous.element) + ")";
    }
  }
}

P.S. Код расчитан на JDK 1.5.

Автор: KatrinIceLand 17.10.2006, 00:38
Цитата

Не реализованные методы будут выбрасывать исключение UnsupportedOperationException, если надо могу их потом реализовать.

Спасибо большое! Этого достаточно, буду разбираться. Пока сдам как есть, остальное сама буду доделывать. 

Автор: LSD 17.10.2006, 00:40
Там самое сложное это listIterator(int index) реализовать. Все остальные методы реализуются с его помощью.

Удачи smile

Автор: KatrinIceLand 17.10.2006, 00:52
 smile Спасибо! Вы мне очень помогли!  smile 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)