【算法刷题】 单链表的快排和归并排序

快排:

 
 struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };



	
	 void swap(ListNode *l, ListNode *r)
	 {
		 int temp = l->val;
		 l->val = r->val;
		 r->val = temp;
	 }

	 ListNode *partion(ListNode *pstart, ListNode *pend)
	 {

		 int povit = pstart->val;
		 ListNode *left=pstart; //point to the less boundary
		 ListNode *right = pstart->next;


		 while (right != nullptr && right != pend->next)
		 {
			 if (right->val < povit)
			 {
				 left = left->next;
				 if(left!=right)
					swap(left, right);
				 
			 }
			 right = right->next;
		 }
		 swap(left, pstart);

		 return left;

	 }

	 void quick_sort(ListNode* pleft, ListNode* pright)
	 {
		 //注意此处的判断条件,因为可能partion到最后一个后,pos->next = nullptr
		 if (pleft == pright || pleft == nullptr) 
			 return;

		 ListNode* pos = partion(pleft, pright);
		 quick_sort(pleft, pos);
		 quick_sort(pos->next, pright);
	 }

	 ListNode *sortList(ListNode *head) {
		 if (head == nullptr)
			 return head;

		 ListNode *endlist = head;
		 while (endlist->next != nullptr)
		 {
			 endlist = endlist->next;
		 }

		 quick_sort(head, endlist);
		 return head;

	 }



归并排序

//链表的归并排序
//合并两个排序链表
ListNode* MergeTwo(ListNode* pleft,ListNode* pright)
{
	if (pleft == nullptr)
		return pright;
	if (pright == nullptr)
		return pleft;
	//确定头节点
	ListNode* pHead = nullptr;
	if (pleft->val < pright->val)
	{
		pHead = pleft;
		pleft = pleft->next;
	}
	else
	{
		pHead = pright;
		pright = pright->next;
	}

	ListNode* temp = pHead;

	while (pleft != nullptr && pright != nullptr)
	{
		if (pleft->val < pright->val)
		{			
			temp->next = pleft;
			pleft = pleft->next;
			temp = temp->next;
			
		}
		else
		{
			temp->next = pright;
			pright = pright->next;
			temp = temp->next;
		}
	}

	if (pleft == nullptr)
		temp->next = pright;
	if (pright == nullptr)
		temp->next = pleft;

	return pHead;

}


ListNode* Mergesort(ListNode* pHead)
{
	if (pHead == nullptr || pHead->next == nullptr)
		return pHead;

	//split list  对半分割 快慢指针 得到的slow为中间点
	ListNode* fast = pHead;
	ListNode* slow = pHead;
	while (fast->next != nullptr && fast->next->next != nullptr)
	{
		fast = fast->next->next;
		slow = slow->next;
	}

	ListNode* Left = pHead;
	ListNode* Right = slow->next;
	slow->next = nullptr;

	ListNode* pLeft = Mergesort(Left);
	ListNode* pRight = Mergesort(Right);

	return MergeTwo(pLeft, pRight);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值