2014-11-16 2 views
0

У меня возникла проблема с сортировкой списка пациентов на основании серьезности и времени прибытия. Может посмотреть, что не так с моим кодом? См. LList.java, метод SortPatient верен?Как отсортировать список интерфейса

ListInterface.java

public interface ListInterface<T> { 

public boolean add(T newEntry); 

public boolean add(int newPosition, T newEntry); 

public T remove(int givenPosition); 

public void clear(); 

public boolean replace(int givenPosition, T newEntry); 

public T getEntry(int givenPosition); 

public boolean contains(T anEntry); 

public int getLength(); 

public boolean isEmpty(); 

public boolean isFull(); 

public int getPosition(T anObject); 

public void SortPatient(ListInterface<Patient> patientList); 
} 

Llist.java

import java.util.Collections; 

import java.util.Comparator; 

import java.util.Date; 


public class LList<T> implements ListInterface<T> { 

private Node firstNode; // reference to first node 
private int length;  // number of entries in list 

public LList() { 
    clear(); 
} 

public LList(T[] arr) { 
    clear(); 
    firstNode = new Node(arr[0], null); 
    Node p = firstNode; 
    for (int index = 1; index < arr.length; index++) { 
     p.next = new Node(arr[index], null); 
     p = p.next; 
     //index must start with 0 
     //or add(arr[index]); 
    } 
    length = arr.length; 

} 

public int getPosition(T anObject) { 
    Node currentNode = firstNode; 
    int position = 0; 
    while (currentNode != null) { 
     position++; 
     if (currentNode.data.equals(anObject)) { 
      return position; 
     } 
     currentNode = currentNode.next; 
    } 

    return -1; 
} 

public final void clear() { 
    firstNode = null; 
    length = 0; 
} 

public boolean add(T newEntry) { 
    Node newNode = new Node(newEntry); 
    // create the new node 

    if (isEmpty()) // if empty list 
    { 
     firstNode = newNode; 
    } else {      // add to end of nonempty list 
     Node currentNode = firstNode;     // traverse linked list with p pointing to the current node 
     while (currentNode.next != null) {  // while have not reached the last node 
      currentNode = currentNode.next; 
     } 
     currentNode.next = newNode; // make last node reference new node 
    } 

    length++; 
    return true; 
} 

public boolean add(int newPosition, T newEntry) { // OutOfMemoryError possible 
    boolean isSuccessful = true; 

    if ((newPosition >= 1) && (newPosition <= length + 1)) { 
     Node newNode = new Node(newEntry); 

     if (isEmpty() || (newPosition == 1)) {  // case 1: add to beginning of list 
      newNode.next = firstNode; 
      firstNode = newNode; 
     } else {              // case 2: list is not empty and newPosition > 1 
      Node nodeBefore = firstNode; 
      for (int i = 1; i < newPosition - 1; ++i) { 
       nodeBefore = nodeBefore.next;  // advance nodeBefore to its next node 
      } 

      newNode.next = nodeBefore.next; // make new node point to current node at newPosition 
      nodeBefore.next = newNode;  // make the node before point to the new node 
     } 

     length++; 
    } else { 
     isSuccessful = false; 
    } 

    return isSuccessful; 
} 

public T remove(int givenPosition) { 
    T result = null;     // return value 

    if ((givenPosition >= 1) && (givenPosition <= length)) { 
     if (givenPosition == 1) {  // case 1: remove first entry 
      result = firstNode.data;  // save entry to be removed 
      firstNode = firstNode.next; 
     } else {       // case 2: givenPosition > 1 
      Node nodeBefore = firstNode; 
      for (int i = 1; i < givenPosition - 1; ++i) { 
       nodeBefore = nodeBefore.next;  // advance nodeBefore to its next node 
      } 
      result = nodeBefore.next.data; // save entry to be removed 
      nodeBefore.next = nodeBefore.next.next; // make node before point to node after the 
     }                // one to be deleted (to disconnect node from chain) 

     length--; 
    } 

    return result;     // return removed entry, or 
    // null if operation fails 
} 

public boolean replace(int givenPosition, T newEntry) { 
    boolean isSuccessful = true; 

    if ((givenPosition >= 1) && (givenPosition <= length)) { 
     Node currentNode = firstNode; 
     for (int i = 0; i < givenPosition - 1; ++i) { 
      // System.out.println("Trace| currentNode.data = " + currentNode.data + "\t, i = " + i); 
      currentNode = currentNode.next;  // advance currentNode to next node 
     } 
     currentNode.data = newEntry; // currentNode is pointing to the node at givenPosition 
    } else { 
     isSuccessful = false; 
    } 

    return isSuccessful; 
} 

public T getEntry(int givenPosition) { 
    T result = null; 

    if ((givenPosition >= 1) && (givenPosition <= length)) { 
     Node currentNode = firstNode; 
     for (int i = 0; i < givenPosition - 1; ++i) { 
      currentNode = currentNode.next;  // advance currentNode to next node 
     } 
     result = currentNode.data; // currentNode is pointing to the node at givenPosition 
    } 

    return result; 
} 

public boolean contains(T anEntry) { 
    boolean found = false; 
    Node currentNode = firstNode; 

    while (!found && (currentNode != null)) { 
     if (anEntry.equals(currentNode.data)) { 
      found = true; 
     } else { 
      currentNode = currentNode.next; 
     } 
    } 

    return found; 
} 

public int getLength() { 
    return length; 
} 

public boolean isEmpty() { 
    boolean result; 

    if (length == 0) { 
     result = true; 
    } else { 
     result = false; 
    } 

    return result; 
} 

public boolean isFull() { 
    return false; 
} 

public String toString() { 
    String outputStr = ""; 
    Node currentNode = firstNode; 
    while (currentNode != null) { 
     outputStr += currentNode.data; 
     currentNode = currentNode.next; 
    } 
    return outputStr; 
} 

private class Node { 

    private T data; 
    private Node next; 

    private Node(T data) { 
     this.data = data; 
     this.next = null; 
    } 

    private Node(T data, Node next) { 
     this.data = data; 
     this.next = next; 
    } 
} // end Node 

public void SortPatient(ListInterface<Patient> patientList) { 
    if (patientList == null) { 
     return; 
    } 

    boolean swapped; 
    Patient patient; 

    do { 
     swapped = false; 
     patient = head; 
     while (patientList.next != null) { 
      if (patient.compareTo(patientList.next) < 1) { 
       swap(patientList.current, patientList.next); 
       swapped = true; 
      } 
      patient = patientList.next; 
     } 
    } while (swapped); 

} 

} 

Patient.java

import java.util.Date; 
import java.util.Collections; 
import java.util.LinkedList; 
import java.util.List; 
import static javafx.scene.input.KeyCode.T; 

public class Patient implements Comparable<Patient> { 

String patientId; 
String patientName; 
String patientGender; 
String patientIcNumber; 
String patientContactNumber; 
Date date; 
int seriousness; 
static int count = 0; 

public Patient() { 
} 

public Patient(String patientId, String patientName, String patientGender, String patientIcNumber, String patientContactNumber, Date date, int seriousness) { 
    this.patientId = patientId; 
    this.patientName = patientName; 
    this.patientGender = patientGender; 
    this.patientIcNumber = patientIcNumber; 
    this.patientContactNumber = patientContactNumber; 
    this.date = date; 
    this.seriousness = seriousness; 
    count++; 

} 

public String getPatientId() { 
    return patientId; 
} 

public void setPatientId(String patientId) { 
    this.patientId = patientId; 
} 

public String getPatientName() { 
    return patientName; 
} 

public void setPatientName(String patientName) { 
    this.patientName = patientName; 
} 

public String getPatientGender() { 
    return patientGender; 
} 

public void setPatientGender(String patientGender) { 
    this.patientGender = patientGender; 
} 

public String getPatientIcNumber() { 
    return patientIcNumber; 
} 

public void setPatientIcNumber(String patientIcNumber) { 
    this.patientIcNumber = patientIcNumber; 
} 

public String getPatientContactNumber() { 
    return patientContactNumber; 
} 

public void setPatientContactNumber(String patientContactNumber) { 
    this.patientContactNumber = patientContactNumber; 
} 

public Date getDate() { 
    return date; 
} 

public void setDate(Date date) { 
    this.date = date; 
} 

public int getSeriousness() { 
    return seriousness; 
} 

public void setSeriousness(int seriousness) { 
    this.seriousness = seriousness; 
} 

public int getCount() { 
    return count; 
} 

@Override 
public String toString() { 
    return patientId + " " + patientName + " " + patientGender + " " + patientIcNumber + " " + patientContactNumber + " " + date + " " + seriousness + "\n"; 
} 

@Override 
public int compareTo(Patient t) { 
    int patientSeriouness = t.seriousness; 
    Date arrival = t.date; 
    if (this.seriousness == patientSeriouness) { 
     return this.date.compareTo(arrival); 
    } else { 
     return Integer.compare(this.seriousness, patientSeriouness); 
    } 
} 

} 

ответ

0

Пара вопросов в вашем коде (я только что прошел через добавить, getentry и сортировка метод):

  • В методе getEntry, помните индекс всегда начинается с 0 и пойти после того, как по длине - 1, так что вы должны изменить наш метод:

    public T getEntry(int givenPosition) { 
    T result = null; 
    
    if ((givenPosition >= 0) && (givenPosition < length)) { 
        Node currentNode = firstNode; 
        for (int i = 0; i < givenPosition; ++i) { 
         currentNode = currentNode.next;  // advance currentNode to next node 
        } 
        result = currentNode.data; // currentNode is pointing to the node at givenPosition 
    } 
    return result; 
    } 
    
  • Изменить вашу реализацию интерфейса и класса, чтобы удалить проходя по ListInterface ссылки и ваша реализация должна выглядеть следующим образом:

    public void SortPatient() { 
    if (firstNode == null) { 
        return; 
    } 
    
    boolean swapped; 
    Node patient; 
    
    do { 
        swapped = false; 
        patient = firstNode; 
        while (patient.next != null) { 
         if (patient.data.compareTo(patient.next.data) > 0) { 
          swap(patient, patient.next); 
          swapped = true; 
         } 
         patient = patient.next; 
        } 
    } while (swapped); 
    } 
    
    
    private void swap(Node patient, Node nextPatient) { 
        T temp = patient.data; 
        patient.data = nextPatient.data; 
        nextPatient.data = temp; 
    } 
    
  • ваш сравнить метод в классе пациентов нуждается некоторые улучшения, и это должно быть, как показано ниже:

    @Override 
    public int compareTo(Patient t) { 
        int patientSeriouness = t.seriousness; 
        Date arrival = t.date; 
        if (this.seriousness == patientSeriouness) { 
         return this.date.compareTo(arrival); 
        } else { 
         return ((Integer)this.seriousness).compareTo(patientSeriouness); 
        } 
    } 
    
  • Последнее, но не менее, ваше LLIST определение класса следует принимать дженерики типа Сравнительное (Как вы используете метод CompareTo), поэтому вам нужно мандат, что и он должен быть определен как

    public class LList<T extends Comparable<T>> implements ListInterface<T> 
    
+0

Я следил за вашей инструкцией, но символ обмена не может быть найден, swap (пациент, пациент.следующий); – user2983387

+0

Извинения, я пропустил это! Отредактировал ответ и спасибо, что привлек его к моему вниманию. – SMA

+0

Хорошо сделано. Спасибо за помощь. Я очень ценю это. – user2983387