【算法】链表的归并排序

https://blog.csdn.net/weixin_39688949/article/details/78472246

复杂度分析:

设置两个指针,一个步长为1, 一个步长为2,当快指针到达尾结点时,慢指针指向中间结点,时间复杂度为O(N);

平分为左链表L1和右链表L2,递归分裂,直到链表为空或者只有一个结点;

将链表L2的每个结点插入到链表L1中,时间复杂度为O(m+n),m、n分别为两条链表的长度。

画出递归树,可知总的时间复杂度为O(N * lgN)。


# include <iostream>
using namespace std;

struct Node {
	int data;
	Node* next;
	Node(int val) {
		data = val;
		next = NULL;
	}
	Node()
	{
		data = 0;
		next = NULL;
	}
};

struct List {
	Node* head;
	Node* tail;
	List(int val)
	{
		head = new Node(val);
		tail = head;
	}
	void append(int val)
	{
		tail->next = new Node(val);
		tail = tail->next;
	}
};

Node* merge(Node* newLeft, Node* newRight) {
	Node * newList;
	Node * tail;

	if (newLeft->data < newRight->data)
	{
		newList = newLeft;
		newLeft = newLeft->next;
	}
	else
	{
		newList = newRight;
		newRight = newRight->next;
	}
	tail = newList;
	tail->next = NULL;

	while (newLeft != NULL || newRight != NULL){
		if (newLeft == NULL){
			tail->next = newRight;
			newRight = NULL;
		}
		else if (newRight == NULL) {
			tail->next = newLeft;
			newLeft = NULL;
		}
		else if (newLeft->data < newRight->data){
			tail->next = newLeft;
			newLeft = newLeft->next;
			tail = tail->next;
			tail->next = NULL;
		}
		else {
			tail->next = newRight;
			newRight = newRight->next;
			tail = tail->next;
			tail->next = NULL;
		}
	}

	return newList;
}

Node* part(Node* head) {
	Node* fast = head->next;
	Node* slow = head;
	while (fast != NULL&&fast->next != NULL){
		fast = fast->next->next;
		slow = slow->next;
	}

	Node* left = head;
	Node* right = slow->next;
	slow->next = NULL;
	return right;
}

Node* listMergeSort(Node* head){
	if (head->next == NULL)
		return head;

	Node* left = head;
	Node* right=part(head);

	Node* newLeft = listMergeSort(left);
	Node* newRight = listMergeSort(right);

	return merge(newLeft, newRight);
}


int main() {
	List list = List(6);
	list.append(3);
	list.append(4);
	list.append(9);
	list.append(8);
	list.append(3);
	list.append(42);
	list.append(25);
	list.append(51);
	list.append(30);
	Node* test = list.head;
	for (int i = 0; i < 10; i++)
	{
		cout << test->data << " ";
		test = test->next;
	}
	cout << endl;

	Node* newHead = listMergeSort(list.head); //这里把list的头节点直接进去了2333333,不优雅.。。。

	Node * temp;
	for (int i = 0; i < 10; i++)
	{
		cout << newHead->data << " ";
		temp = newHead;
		if (newHead->next != NULL)
			newHead = newHead->next;
		delete temp;
	}
	cout << endl;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值