【问题标题】:Problem when alphabetically inserting a node into a doubly linked list按字母顺序将节点插入双向链表时出现问题
【发布时间】:2021-01-20 19:37:19
【问题描述】:

我正在尝试为双向链表编写插入方法,当我将节点放入列表时,它按字母顺序插入。这个想法是我将使用 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;
                }
            }
           
        }
    }

【问题讨论】:

  • 仅供参考: Java 命名约定规定类名应以大写字母开头,因此 node 应为 Node

标签: java algorithm sorting doubly-linked-list


【解决方案1】:

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

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;
        }
       
    }
}

【讨论】:

  • 如果此答案解决了您的所有问题/疑问,请随时将其标记为已解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 2011-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多