链表的排序插入方法?

时间:2016-03-11 06:18:12

标签: java sorting linked-list singly-linked-list

所以我需要创建一个方法,将按升序顺序将项目插入到链接列表中。我已经尝试了好几个小时,无法让它发挥作用。此实现仅添加第一个元素,并且永远不会输入循环。但是,当我尝试其他任何东西时,我得到一个无限循环或空指针异常。请帮助我指出正确的方向。

 public class List<T extends Comparable<T>> implements Iterable<T> { 
          ........
           public void sortedOrderInsert(T newElt) {
                Node<T> n = new Node<T>(newElt);
                Node<T> current = head;
                Node<T> prev = head;
                boolean added = false;
                if (head == null) {
                    head = n;
                    count++;
                } else {
                    while (current.next != null && added == false) {
                        prev = current;
                        current = current.next;
                        if (current.data.compareTo(newElt) >= 0 ) {
                            added = true;
                            n = current;
                            prev = n;
                            count++;    
                        }
                        else if (current.next == null) {
                            current.next = n;
                            current = current.next;
                            count++;
                        }
                    }
                }
            }
         }

这是我的Node类。

private static class Node<D extends Comparable<D>> {
        private D data;
        private Node<D> next;

        public Node(D data) {
            this.data = data;
            next = null;
        }
    }

0 个答案:

没有答案