Лучший способ отследить предыдущий узел в моем sortedLinkedList? - PullRequest
0 голосов
/ 15 апреля 2020

Мой преподаватель в моем классе CS попросил меня отсортировать LinkedList. Метод, который я пытаюсь использовать для сортировки связанного списка, заключается в том, чтобы делать это всякий раз, когда новый int добавляется в связанный список. Суть проблемы заключается в том, что метод, который он рекомендовал использовать для сортировки связанного списка, требует, чтобы я каким-то образом отслеживал, каким был предыдущий элемент в связанном списке, несмотря на то, что это список с одиночной связью, а не список с двойной связью. Я удостоверился, что спросил его, хочет ли он, чтобы я создал двусвязный список, или нет, и он ответил, что это не то, о чем он говорил. Самым большим препятствием является то, что во втором блоке кода else-if внутри моей функции добавления, где этот код здесь:


if ((int) input < (int) current.value){
                   LinkedListNode newnode = new LinkedListNode(input, current);

Я не уверен, как отследить предыдущий. Каков наилучший способ сделать это?

public class SortedLinkedList<T extends Comparable<T>> {

  private LinkedListNode head;

  SortedLinkedList() {
    head = null;
  }

  // Start from head
  // Check its value
  // 2 nodes at once
  // Check previous node
  // Check next node
  // Check after head before end
  // Check last element

  public synchronized void add(T input) {

    LinkedListNode current;

    if (head == null) {

      LinkedListNode newNode = new LinkedListNode(input, null);
      head = newNode;
      head.setIndex(0);

    } else if ((int) input < (int) head.value) {

      current = head;

      LinkedListNode newNode = new LinkedListNode(input, null);
      head = newNode;

      newNode.setNext(current);
    } else if ((int) input > (int) head.value) {
      current = head;

      while (current.getNext() != null) {

        if ((int) input < (int) current.value) {
          LinkedListNode newnode = new LinkedListNode(input, current);
        }

        current = current.getNext();
      }

    } else {

      current = head;
      int indexCounter = head.index;
      while (current.getNext() != null) {

        current = current.getNext();
        indexCounter++;

        int currentgetNEXTHOLDER;
        int currentValueHolder;

        // Loops through the functuon and switches any values less than the previous

        if ((int) current.getNext().value < (int) current.value) {
          currentgetNEXTHOLDER = (int) current.getNext().value;
          currentValueHolder = (int) current.value;

          current.getNext().value = currentValueHolder;
          current.value = currentgetNEXTHOLDER;
        }
      }

      current.setIndex(indexCounter);
      LinkedListNode mynewNode = new LinkedListNode(input, null);
      current.setNext(mynewNode);
    }
  }

  public T getValue(int index) {

    T keeptheValue = null;
    LinkedListNode current = getHead();

    while (current.getNext() != null) {
      if (current.index == index) {
        keeptheValue = (T) current.value;
      }

      current = current.getNext();
    }

    return keeptheValue;
  }

  public Boolean search(T value) {
    LinkedListNode current = getHead();
    boolean isitThere = false;
    while (current.getNext() != null) {
      if (current.value == value) {
        isitThere = true;
      }
    }
    return isitThere;
  }

  public LinkedListNode getHead() {
    return head;
  }

  public String printAllValues() {
    LinkedListNode current = head;
    String intTOStringchain = "";
    while (current.getNext() != null) {

      intTOStringchain = intTOStringchain + "," + Integer.toString((int) current.value);
    }

    return intTOStringchain;
  }

  class LinkedListNode<T extends Comparable<T>> {

    public T value;
    private LinkedListNode next;
    public int index;
    public LinkedListNode previous;

    public LinkedListNode(T value, LinkedListNode next) {
      this.value = value;
      this.next = next;
    }

    public LinkedListNode getNext() {
      return next;
    }

    public void setNext(LinkedListNode next) {
      this.next = next;
    }

    public LinkedListNode getPrevious() {
      return previous;
    }

    public void setPrevious(LinkedListNode previous) {
      this.previous = previous;
    }

    public boolean greaterThan(T otherValue) {

      int definingValue = otherValue.compareTo(value);
      if (definingValue > 0) {
        return true;
      } else {
        return false;
      }
    }

    public void setIndex(int index) {
      this.index = index;
    }
  }
}

Выше приведен весь код в классе, любая помощь будет оценена.

Ответы [ 2 ]

1 голос
/ 15 апреля 2020

Псевдокод для метода добавления:

prev = null
curr = head
while curr != null and curr.value <= value:
    prev = curr
    curr = curr.next
if prev == null then:
    head = new Node(value, curr)
else:
    prev.next = new Node(value, curr)

Ваш код слишком сложен. Это действительно так просто.

0 голосов
/ 15 апреля 2020

если ваш список получен из java.util.List

int idx = Collections.binarySearch( list, valueToAdd );
if( idx < 0 )
  idx = -idx - 1;
list.add( idx, valueToAdd );

если вы добавляете все элементы указанным выше способом, все элементы в списке будут отсортированы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...