2015-04-23 136 views
-2

這是我的code.I想知道爲什麼它不起作用。C++按升序排序鏈接列表

sll_node *sortList(sll_node *head) 
{ 

int temp=head->value; 
if(head!=NULL||temp>head->next->value) 
{ 
    head->value=head->next->value; 
    head->next->value=temp; 
} 
else 
{ 
    sortList(head->next); 
    sortList(head->next->next); 
    sortList(head->next); 
}   
    return head; 
} 
+1

你可以請指定你的意思是**「它不工作。」** –

+1

請使用調試器。上述代碼中的問題不是太深奧。運行一個小列表,並在其上運行'sortList's操作會顯示答案。 – Pradhan

+2

或者剛開始添加打印語句,這應該足以解決這個問題。在你已經解除引用'head'之後,你正在檢查'NULL' *。 – Praetorian

回答

0

你已經顯示的代碼中的主要問題是你知道它們是否有效之前使用指針。因此,在你可以指定temp-> head-> value或使用head-> next之前,你必須確保head不等於NULL。在使用head-> next-> value或head-> next-> next之前,您必須確保head-> next不等於NULL。

試試這個:

sll_node *sortList(sll_node *head) 
{ 
    if(head != NULL) 
    { 
     int temp=head->value; 
     if (head->next != NULL) 
     { 
      if (temp > head->next->value) 
      { 
       head->value=head->next->value; 
       head->next->value=temp; 
      } 
      else 
      { 
       sortList(head->next); 
      } 
     } 
    } 
    return head; 
}  

還有就是你會遇到你運行此之後,另一個問題。

如果列表爲:[3,2,1,4]
第一次通過排序列表將使:[2,3,1,4]
第二遍將導致:[2, 1,3,4]
第三個也是最後一個通過會導致:[2,1,3,4]

我會讓你嘗試解決下一步。我會回答具體的問題,如果你有他們一些更多的努力,你有他們。