링크 된 목록을 만들려고합니다 (자바의 기본값을 사용하지 않고 내 자신을 정의했습니다). 연결된 목록은 어떤 순서로 데이터를 추가 할 수 있어야합니다. 사용자가 동일한 순서로 1, 3 및 2를 삽입하려고합니다. "2"는 3보다 먼저 삽입해야하며 결과 링크리스트는 1, 2 및 3이어야합니다.Sorted가있는 사용자 지정 링크 목록
무엇보다도 제네릭을 사용하여 모든 작업을 수행해야합니다.
맞춤 링크 된 목록에 대한 다음 클래스를 만들었 으면 정렬 된 순서로 삽입하는 데 도움이 필요합니다.
package customlinkedlist;
public class Node<T> {
private T data;
private Node<T> next;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
}
그런 다음
package customlinkedlist;
public interface CustomLinkedList<T> {
Node<T> insert(T data);
}
그리고
package customlinkedlist;
public class CustomLinkedListimpl<T> implements CustomLinkedList<T> {
private Node<T> head;
public CustomLinkedListimpl() {
head = new Node<T>();
head.setNext(null);
head.setData(null);
}
public Node<T> insert(T data) {
Node<T> nodeToInsert = null;
if (head.getNext() == null) {
nodeToInsert = new Node<T>();
nodeToInsert.setData(data);
nodeToInsert.setNext(null);
head.setNext(nodeToInsert);
} else {
Node<T> tempNode = head;
while(tempNode.getNext() != null) {
tempNode = tempNode.getNext();
}
nodeToInsert = new Node<T>();
nodeToInsert.setData(data);
nodeToInsert.setNext(null);
tempNode.setNext(nodeToInsert);
}
return nodeToInsert;
}
public void printList() {
if (head == null) {
System.out.println("List is null.");
return;
}
Node<T> tempNode = head.getNext();
System.out.print(tempNode.getData());
while (tempNode.getNext() != null) {
tempNode = tempNode.getNext();
System.out.print(" --> " + tempNode.getData());
}
}
}
각각의 구현 -
그리고 인터페이스 -이 당신은 당신의 정렬을 generify하는 Comparable를 사용할 수있는 클라이언트가package customlinkedlist;
public class CustomLLClient {
public static void main(String[] args) {
CustomLinkedListimpl<Integer> customLinkedList = new CustomLinkedListimpl<Integer>();
customLinkedList.insert(1);
customLinkedList.insert(3);
customLinkedList.insert(2);
customLinkedList.printList();
}
}
부적절한 들여 저를 용서해주세요 도구들. – Sam
찾았지만 어떤 경우에는 정렬 할 수 있지만 해결 방법은 있지만 http://stackoverflow.com/questions/19802104/how-would-i-make-my-custom-generic-type-linked-list-in-java-sorted 제네릭을 사용하지 않습니다. – Sam
들여 쓰기 및 형식 지정을 위해 Alex에게 감사드립니다. – Sam