C++ sort linked list in ascending order -


this code.i wondering why doesn't work.

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

the main problem in code have shown using pointers before knowing if valid.

so before can assign temp head->value or use head->next, have make sure head not equal null. before use head->next->value or head->next->next, have make sure head->next not equal null.

try this:

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

there problem run after run this.

if list is: [3, 2, 1, 4]
first pass through sort list make: [2, 3, 1, 4]
second pass result in: [2, 1, 3, 4]
third , final pass result in: [2, 1, 3, 4]

i'll let try , solve next step. i'll answer specific questions if have them once you've put more effort in.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -