Sorting a linked list

前端 未结 8 748
-上瘾入骨i
-上瘾入骨i 2020-11-29 09:26

I have written a basic linked list class in C#. It has a Node object, which (obviously) represents every node in the list.

The code does not use IEnumerable, however

8条回答
  •  没有蜡笔的小新
    2020-11-29 10:20

    This might not be the best solution, but it's as simple as I can come up with. If anyone can think of something simpler but still fast, I'd love to hear it.
    SORRY THAT IT'S C++ it should translate.

    List * SortList(List * p_list)
    {
         if(p_list == NULL || p_list->next == NULL) 
              return p_list;
    
         List left, right;
         List * piviot = p_list;
         List * piviotEnd = piviot;
         List * next = p_list->next;
         do
         {
                  p_list = next;
                  next = next->next;
                  //FIGURE OUT WHICH SIDE I'M ADDING TO.
                  if(p_list->data > piviot->data ) 
                      right.InsertNode(p_list);
                  else if(p_list->data < piviot->data)
                      left.InsertNode(p_list);
                  else
                  {   //we put this in it's own list because it doesn't need to be sorted
                      piviotEnd->next = p_list;
                      piviotEnd= p_list;
                  }  
         }while(next);
    
         //now left contains values < piviot and more contains all the values more
         left.next = SortList(left.next);
         right.next = SortList(right.next);
    
         //add the piviot to the list then add the rigth list to the full list
         left.GetTail()->next = piviot;
         piviotEnd->next = right.next;
    
         return left.next;
    }
    

提交回复
热议问题