C语言链表(头节点也包含数据)的冒泡排序法

网上的都是写头节点不包含数据的写法,我习惯头节点也存着数据,就当做个记录

#pragma warning(disable : 4996)
#include 
#include 
#include 
using namespace std;

struct listnode
{
	int data;
	struct listnode* next;
};

listnode* buildnode(int num)
{

	listnode* head = NULL;
	listnode* ptr1 = head, * ptr2 = head;
	for (int i = 0; i < num; i++)
	{
		ptr2 = ptr1;
		cout << "请输入你的数据" << endl;
		int m_data;
		cin >> m_data;
		if (head==NULL)
		{
			head = (listnode*)malloc(sizeof(listnode));
			ptr1 = head;
			ptr2 = head;
			head->data = m_data;
		}
		else
		{
			ptr1 = (listnode*)malloc(sizeof(listnode));
			ptr1->data = m_data;
			ptr2->next = ptr1;
		}
	}

	return head;
}

listnode* bubble(listnode* head,int num)
{
	listnode* former=head->next, *back=head, * temp=head;
	int num2 = 0;
	for (int j = 0; j < num-1; j++)
	{
		num2 = num - 1 - j;
		back = head;
		former = head->next;
		temp = head;
		while(num2--)
		{
			if (back->data > former->data)
			{
				if (back == head)//现在讨论刚好back指向头节点的情况
				{
					back->next = former->next;
					former->next = back;//交换完毕

					//为了继续保持former在前,back在后,且头节点要更换
					listnode* swap = former;
					former = back;
					back = swap;
					head = back;
					temp = head;
					
					//现在former和back都往前挪一步
					former = former->next;
					back = back->next;

				}

				else//back不是头节点的情况,要保证temp指针的next是back,back的next是former
				{
					back->next = former->next;
					former->next = back;
					temp->next = former;//交换完成,接下来就是继续保持former在前,back在后

					listnode* swap = former;
					former = back;
					back = swap;
					

					//现在former和back和temp都往前挪一步
					former = former->next;
					back = back->next;
					temp = temp->next;
				}
			}

			else
			{
				if (back == head)
				{
					former = former->next;
					back = back->next;
				}
				else
				{
					former = former->next;
					back = back->next;
					temp = temp->next;
				}
			}
		}
	}
	
	return head;
	

}

int main()
{
	cout << "链表有几个元素" << endl;
	int num = 0;
	cin >> num;
	listnode* head = buildnode(num);
	head = bubble(head,num);
	listnode* ptr = head;
	while (ptr)
	{
		cout << ptr->data << " ";
		ptr = ptr->next;
	}
	return 0;
}

可恶啊,为什么那么长呜呜 

和冒泡排序法一样,外循环次数是总元素数-1,内循环次数是总元素数-1-外循环次数

你可能感兴趣的:(链表,c语言,数据结构,c++)