我想创建一个链表(不使用Java的默认,而是我自己定义)。 链表应该足够能够以某种顺序添加数据。 与用户一样,尝试按给定顺序插入1,3和2。 “2”应该在3之前插入,并且生成的链表应该有1,2和3.自定义LinkedList与排序
最重要的是,一切都应该使用泛型(我想学习它)。
为自定义链接列表创建以下类,只需要帮助按排序顺序提供插入。
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);
}
和各自implementation-
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());
}
}
}
这是客户端接收机类
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 2014-12-03 01:03:30
我发现这个http://stackoverflow.com/questions/19802104/how-would-i-make-my-custom-generic-type-linked-list-in-java-sorted虽然它解决了一些如何,但在案件排序不使用泛型。 – Sam 2014-12-03 01:04:08
谢谢亚历克斯的缩进和格式。 – Sam 2014-12-03 01:05:43