0

插入節點在一個雙向有序鏈表的每個插入之後,該列表應被排序插入在排序雙向鏈表的節點

節點被定義爲

struct Node 
    { 
    int data; 
    Node *next; 
    Node *prev; 
    } 

和功能的邏輯被寫入下面..

Node* SortedInsert(Node *head,int data) 
{ 
    // Complete this function 
    // Do not write the main method. 
    struct Node *newn= (struct Node*)malloc(sizeof(struct Node*)); 
    newn->data= data; 
    newn->next= newn->prev= NULL; 

    struct Node *trav=head, *pre=NULL; 

    if(head==NULL) 
     head= newn; 
    else if(newn->data <= trav->data) 
    { 
     newn->next= trav; 
     trav->prev= newn; 
     head= newn; 
    } 
    else 
    { 
     while(trav->data <= newn->data) 
     { 
      pre= trav; 
      trav=trav->next; 
     } 
     pre= trav; 
     trav=trav->next; 

     newn->next= trav; 
     trav->prev= newn; 
     pre->next= newn; 
     newn->prev= pre; 
    } 
    return head; 
} 

請讓我知道什麼是邏輯問題

回答

2

呦ü正在一個小錯誤,首先的空間分配是這樣的:

struct Node *newn= (struct Node*)malloc(sizeof(struct Node)); 

,右else條件是:

else 
{   
while(trav!=NULL&&trav->data <= newn->data) 
{ 
    pre= trav; 
    trav=trav->next; 
} 
newn->prev=pre; 
newn->next=trav; 
pre->next=newn; 
if(trav!=NULL) 
    trav->prev=newn; 
}