单链表的冒泡排序

单链表的冒泡排序

1 交换数据域

        (1) 带头结点的单链表的冒泡排序(交换数据域)

void ListBubbleSort(Node *headNode, int size)//  headNode:头节点;size:链表长度
{
	if (nullptr == headNode || size <= 0)
		return;
	for (int i = 0; i < size - 1; i++)
	{
		bool flag = false;
		Node *p = headNode->next;
		for (int j = 0; j < size - 1 - i; j++)
		{
			if (p->value > p->next->value)
			{
				swap(p->value, p->next->value);
				flag = true;
			}
			p = p->next;
		}
		if (!flag)
			break;
	}
}

        (2) 不带头结点的单链表的冒泡排序(交换数据域)

void bubbleSortList(listNode *head, int size)//  head:头指针;size:链表长度
{ 
	if (nullptr == head || size <= 0)
		return;
	for (int i = 0; i < size - 1; i++)
	{
		bool flag = false;
		listNode *p = head;
		for (int j = 0; j < size - 1 - i; j++)
		{
			if (p->value > p->next->value)
			{
				swap(p->value, p->next->value);
				flag = true;
			}
			p = p->next;
		}
		if (!flag)
			break;
	}
}

2 交换指针域

       (1) 带头结点的单链表的冒泡排序(交换指针域)

void ListBubbleSort(listNode *headNode)  //headNode:头节点
{
	if (nullptr == headNode)
		return;
	listNode *tail = nullptr;
	while (headNode->next->next != tail)
	{
		listNode *p = headNode;
		listNode *q = headNode->next;
		while (q->next != tail)
		{
			if (q->value > q->next->value)
			{
				p->next = q->next;
				q->next = q->next->next;
				p->next->next = q;
				q = p->next;
			}
			p = p->next;
			q = q->next;
		}
		tail = q;
	}
}

 

点赞