当前位置:   article > 正文

单链表快速排序_带头结点的单链表可以快速排序吗?

带头结点的单链表可以快速排序吗?

2015.11.27  面试一点资讯 ,面试官是很nice的校友师兄,无奈基本功太差,跪了!

  1. #include <iostream>
  2. using namespace std;
  3. #define random(x) (rand()%x)
  4. struct ListNode
  5. {
  6. int value;
  7. ListNode* next;
  8. };
  9. void create_list(ListNode* head)
  10. {
  11. ListNode* pNode = head;
  12. for(int i = 0; i < 10; i++)
  13. {
  14. ListNode* pNew = new ListNode;
  15. pNew->value = random(10);
  16. pNew->next = NULL;
  17. pNode->next = pNew;
  18. pNode = pNode->next;
  19. }
  20. }
  21. void print_list(ListNode* head)
  22. {
  23. ListNode* pNode = head->next;
  24. while(pNode != NULL)
  25. {
  26. cout << pNode->value << ' ';
  27. pNode = pNode->next;
  28. }
  29. cout << endl;
  30. }
  31. void quick_sort(ListNode* head, ListNode* tail)
  32. {
  33. if(head->next == tail || head->next->next == tail)
  34. return;
  35. ListNode* mid = head->next;
  36. ListNode* pLess = head;
  37. ListNode* pGreater = mid;
  38. int pivot = mid->value;
  39. ListNode* pNode = mid->next;
  40. while(pNode != tail)
  41. {
  42. if(pNode->value < pivot)
  43. {
  44. pLess->next = pNode;
  45. pLess = pNode;
  46. }
  47. else
  48. {
  49. pGreater->next = pNode;
  50. pGreater = pNode;
  51. }
  52. pNode = pNode->next;
  53. }
  54. pLess->next = mid;
  55. pGreater->next = tail;
  56. quick_sort(head, mid);
  57. quick_sort(mid, tail);
  58. }
  59. int main()
  60. {
  61. ListNode* head = new ListNode;
  62. head->value = -1;
  63. head->next = NULL;
  64. create_list(head);
  65. print_list(head);
  66. quick_sort(head, NULL);
  67. print_list(head);
  68. return 0;
  69. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/1006907
推荐阅读
相关标签
  

闽ICP备14008679号