java - 在预先排序的链表中插入一个节点

标签 java data-structures linked-list doubly-linked-list

我一直在研究关于 hacker rank 的链表问题,我目前正在解决这个问题,它会要求你在一个排序的双向链表中插入一个节点。

这是我用Java写的逻辑

Node SortedInsert(Node head,int data) {

    Node newNode = new Node();
    Node temp = head;
    newNode.data = data;
    newNode.next = null;
    newNode.prev = null;

    if(head == null){
        head = newNode;
    }else{
        while(data > temp.data && temp.next != null){
            temp = temp.next;
        }
        if(temp == head){
            newNode.next = temp;
            temp.prev = newNode;
            head = newNode;
        }else if(data > temp.data){
            newNode.prev = temp;
            temp.next = newNode;
        }else{
            newNode.prev = temp.prev;
            newNode.next = temp;
            temp.prev.next = newNode;
            temp.prev = newNode;
        }

    }

  return head;
}

这是我得到的错误。

Your Output (stdout)
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function. 
2. There is a problem with your logic
Wrong Answer!
Some possible errors:
1. You returned a NULL value from the function. 
2. There is a problem with your logic

我不知道我做错了什么。我真的很想知道我哪里做错了。我知道在网上很容易找到答案,但我想如果有人能纠正我的错误,我会学到最好的东西。

最佳答案

问题是您总是在第一个元素之前插入列表中的第二个元素。请考虑下图:

让链表初始为空。现在您按照您的算法插入 1head == null 情况被触发,head 现在指向 newNode

x<-1->x
   |
  HEAD

现在,您尝试在列表中插入 2。您会看到 while 循环结束并且 temp 现在指向 head,触发后面的 if 条件 (if(temp == 头))。

x<-1->x
   |
  HEAD, temp

这会插入 2(不正确!)before temp

x<-2<=>1->x
   |
  HEAD

交换条件的顺序应该可以解决问题:

    if(data > temp.data) {    // First, check if you need to insert at the end.
        newNode.prev = temp;
        temp.next = newNode;
    } else if(temp == head) { // Then, check if you need to insert before head.
        newNode.next = temp;
        temp.prev = newNode;
        head = newNode;
    } else {                  // Otherwise, insert somewhere in the middle.
        newNode.prev = temp.prev;
        newNode.next = temp;
        temp.prev.next = newNode;
        temp.prev = newNode;
    }

关于java - 在预先排序的链表中插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811285/

相关文章:

java - 向运行应用程序的每个人发送通知,Android

c - 在c中的结构内声明数组

c# - List<> 集合成员在不应该更改时更改

c - 带有不需要的零的链表

Java 元组/对

java - 如何创建一个 JButton,文本位于按钮左侧,图标与按钮右侧分开

Java:嵌套 Hashmap 的问题

c - 运行时检查失败 #3 - 变量 'name_t' 未经初始化就被使用

java - 获取单词/字符串数组的含义

algorithm - 选择随机元素的数据结构?