单链表的三种排序算法

来源:互联网 发布:傲视天地 源码 编辑:程序博客网 时间:2024/06/05 06:23

1 插入排序的变形

struct ListNode {      int val;      ListNode *next;      ListNode(int x) : val(x), next(NULL) {}  };    class Solution {public:ListNode* sortList(ListNode* head) {if (head == NULL)return NULL;//p保存有序链表的头部位置 q保存有序链表的尾部位置 t指向未排序部分的开始位置ListNode *p = head;ListNode *q = head;ListNode *t = head->next;q->next = NULL;//temp作为临时指针方便后面使用ListNode *temp = NULL;while (t){//小于最小位置直接插入到链表头部if (p->val >= t->val){temp = t->next;t->next = p;p = t;t = temp;}//大于最大位置插入到链表结尾else if (q->val <= t->val){temp = t->next;q->next = t;q = q->next;q->next = NULL;t = temp;}//在中间位置需要查找并插入else{ListNode *m1 = p;ListNode *m2 = p->next;temp = t->next;while (m2){if (m2->val >= t->val){t->next = m1->next;m1->next = t;break;}m1 = m1->next;m2 = m2->next;}t = temp;}}return p;}};
2 归并排序

class Solution {private:void mergeSort(ListNode *&head){ListNode *slow = head;ListNode *fast = head;ListNode *p = NULL;//找到之间位置while (fast&&fast->next){p = slow;slow = slow->next;fast = fast->next->next;}if (!p)return;//排序后半段元素mergeSort(slow);p->next = NULL;//排序前半段元素mergeSort(head);//合并结果head=merge(head,slow);}ListNode* merge(ListNode *pre, ListNode *last){ListNode *head = new ListNode(0);ListNode *p = head;while (pre&&last){if (pre->val >= last->val){p->next = last;last = last->next;p = p->next;p->next = NULL;}else{p->next = pre;pre = pre->next;p = p->next;p->next = NULL;}}if (pre){p->next = pre;}else if (last){p->next = last;}pre = head->next;delete head;return pre;}public:ListNode* sortList(ListNode* head) {if (head == NULL)return NULL;    mergeSort(head);return  head;}};

第三种是快排参考的下面这位的:

http://blog.csdn.net/doufei_ccst/article/details/22220661

class Solution {  public:      ListNode* getPartation(ListNode *start, ListNode *end)      {          if (start == end) return start ;            ListNode *p1 = start ;          ListNode *p2 = p1->next ;          int key = start->val ;            while(p2 != end)          {              if (p2->val < key)              {                  p1 = p1->next ;                  swap(p1->val, p2->val) ; //找到一个比key小的数字,与p1到p2间的数交换,              }                                       //这之间的数都大于等于key              p2 = p2->next ;          }          swap(start->val, p1->val) ; //找到划分位置          return p1 ;      } ;        void QuickSort(ListNode* start, ListNode *end)      {          if (start != end)          {              ListNode *pt = getPartation(start, end) ;              QuickSort(start, pt) ;              QuickSort(pt->next, end) ;          }      }        ListNode *sortList(ListNode *head) {          QuickSort(head, NULL) ;          return head ;      }  };    void insertBack(ListNode** head, ListNode** tail,  ListNode* n) //从尾部插入  {         if (n)      {          if (*head == NULL)          {              *head = n ;              *tail = n ;          }          else          {              (*tail)->next = n ;              *tail = n ;          }      }  };



0 0