按字母顺序将节点插入双向链表时出现问题

问题描述

我正在尝试为双向链接列表编写一种插入方法,其中,当我将节点放入列表中时,将按字母顺序将其插入。这个想法是,我将遍历一个curnode,如果newNode在curnode之前,我将newNode放在curnode之前。到目前为止,我编写的代码可用于将1个节点插入列表,但是第二部分存在问题,需要检查顺序和放置位置。我应该如何更改程序以使其正常运行?有了代码,我现在只可以插入1个元素(头)。

void insert(String x){
        node curnode = head;
        node newNode = new node(x);

        //list is empty so insert as normal - [works fine]
        if (head == null){
            head = newNode;
            head.prev = null;
            head.next = null;
            tail = newNode;
        }
        //Now insert node with respect to alphabetical order - [problem area]
        else {
           
            // while the list isn't empty 
            while (curnode != null){

                // if newNode alphabetically comes before the curnode then place before
                if (curnode.data.compareto(newNode.data) > 0){
                    node temp = curnode.prev;
                    curnode.prev = newNode;
                    newNode.next = curnode;
                    newNode.prev = temp;
                    break;
                }
            }
           
        }
    }

解决方法

您的实现缺少一些东西。将其与此可行的解决方案进行比较:

void insert(String x){
    node curnode = head;
    node lastnode = null;
    node newNode = new node(x);
    
    //list is empty so insert as normal - [works fine]
    if (head == null){
        head = newNode;
        head.prev = null;
        head.next = null;
        tail = newNode;
    }
    //Now insert node with respect to alphabetical order - [problem area]
    else {
        // while the list isn't empty 
        while (curnode != null){
            // if newNode alphabetically comes before the curnode then place before
            if (curnode.data.compareTo(newNode.data) > 0){
                
                node temp = curnode.prev;
                curnode.prev = newNode;
                newNode.next = curnode;
                newNode.prev = temp;
                if(temp != null) {
                    temp.next = newNode;
                } else {
                    // If newnode gets inserted in the head
                    head = newNode;
                }
                break;
            }
            
            lastnode = curnode;
            curnode = curnode.next;
        }
        if (curnode == null) {
            // insert to the last
            lastnode.next = newNode;
            newNode.prev = lastnode;
            tail = newNode;
        }
       
    }
}