首页 > 代码库 > 单链表的排序 快速排序 归并排序 quicksort mergesort

单链表的排序 快速排序 归并排序 quicksort mergesort

原理都很简单,关键是某些边界能否正确写对:


#include<iostream>
#include<stdio.h>

using namespace std;
class Node {
public:
  int val;
  Node* next;
  Node(int val = 0):val(val),next(NULL){
  }
};


Node* quicksort(Node* head, Node* tail) {

  Node *res1 = NULL, *res2 = NULL;
  Node *p1 = new Node(0), *p2 = new Node(0), *cur = head;
  Node *cur1 = p1, *cur2 = p2;
  Node *pivot = head;
  if (head == NULL || head->next == tail || head == tail)
    return head;

  cur = cur->next;
  while (cur != tail) {
    if(cur->val < pivot->val) {
      cur1->next = cur;
      cur1 = cur1->next;
    }
    else {
      cur2->next = cur;
      cur2 = cur2->next;
    }
    cur = cur->next;
  }
  cur1->next = pivot;
  pivot->next = p2->next;
  cur2->next = tail;
  
  res1 = quicksort(p1->next, pivot);
  res2 = quicksort(p2->next, tail);
  pivot->next = res2;
  delete p1, p2;

  return res1 == NULL ? pivot : res1;
}
Node* mergesort(Node* head) {
  Node *p1 = head, *p2 = NULL, *cur1 = head, *cur2 = head, *dummy = new Node(0), *cur = dummy, *res = NULL;
  
  if (head == NULL || head->next == NULL)
    return head;
  while (cur2 != NULL && cur2->next != NULL && cur2->next->next != NULL) {
    cur1 = cur1->next;
    cur2 = cur2->next->next;
  }
  p2 = cur1->next;
  cur1->next = NULL;

  cur1 = mergesort(p1);
  cur2 = mergesort(p2);

  while (cur1 && cur2) {
    if (cur1->val < cur2->val){
      cur->next = cur1;
      cur1 = cur1->next;
    }
    else {
      cur->next = cur2;
      cur2 = cur2->next;
    }
    cur = cur->next;
  }
  if (cur1)
    cur->next = cur1;
  else
    cur->next = cur2;
  res = dummy->next;
  delete dummy;
  return res;
}
int main() {

  //Node arr[] = {Node(9), Node(8), Node(7), Node(6), Node(5), Node(4), Node(3), Node(2), Node(1)};
  Node arr[] = {Node(1), Node(2), Node(3), Node(3), Node(5), Node(6), Node(7), Node(8), Node(9)};

  for (int i = 0; i < sizeof(arr) / sizeof(arr[0]) - 1; ++i)
    arr[i].next = &arr[i+1];

  //Node *res = quicksort(&arr[0], NULL);
  //res = quicksort(NULL, NULL);
  Node *res = mergesort(&arr[0]);
  return 0;
}