有人可以帮我处理我的分类链表。它应该按字母顺序打印东西。我有两个问题。
1.当我第一次添加numNodes = 1时,第一个自动消失(在这种情况下,Elaine消失)。 2.随后,应该是最后一个的项目仍然是第一个,而其余项目排列很好。
101 public void addOrdered(E item) {
102 ListNode<E> newNode = new ListNode<E> (item, null);
103 if(numNodes == 0) {
104 this.addFirst(item);
105 System.out.println(numNodes);
106 return;
107 }
108 else if(numNodes == 1) {
109 ListNode<E> curr = head;
110 // if alphabetically in front, add in front
111 if((newNode.getElement()).compareTo(curr.getElement())<0) {
112 System.out.println("ADD IN FRONT");
113 this.addFirst(item);
114 return;
115 }
116 // if alphabetically behind, add behind
117 else {
118 System.out.println("ADD IN BEHIND");
119 curr.setNext(newNode);
120 }
121 }
122 else { //find position to add in between
123 ListNode<E> curr = head.getNext(), prev = head;
124 while((curr != null) && ((newNode.getElement()).compareTo(curr.getElement())>0 )) {
125 prev = curr;
126 curr = curr.getNext();
127 }
128 newNode.setNext(curr);
129 prev.setNext(newNode);
130 }
131 numNodes++;
132 System.out.println(numNodes);
133 }
134 }
我的输入是
Elaine Diana Avery Candy Bubble
我的输出是
1
[Elaine]
ADD IN FRONT
[Diana]
3
[Diana, Avery]
4
[Diana, Avery, Candy]
5
[Diana, Avery, Bubble, Candy]
List:
[Diana, Avery, Bubble, Candy]