簡體   English   中英

在預排序的鏈接列表中插入節點

[英]Inserting a node in a pre sorted linked list

我一直在瀏覽關於黑客排名的Linkedlist問題,我目前正在解決這個問題,它會要求你在一個有序的雙鏈表中插入一個節點。

這是我用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

我不知道我做錯了什么。 我真的想知道我哪里出錯了。 我知道很容易在網上找到答案,但我想如果有人能糾正我的錯誤,我會學到最好的。

問題是你總是在第一個元素之前插入第二個元素。 請考慮以下插圖:

讓鏈表最初為空。 現在,您按照算法插入1 head == null情況被觸發, head現在指向newNode

x<-1->x
   |
  HEAD

現在,您嘗試在列表中插入2 你會看到while循環結束, temp現在指向head ,觸發后面的if條件( if(temp == head) )。

x<-1->x
   |
  HEAD, temp

這會 temp 之前插入2 (錯誤!)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM