用链表实现冒泡排序!

一、问题描述

存储数据不仅数组可以,链表也行。那么如何用链表实现冒泡排序呢?

我们需要把数据存储在链表中,然后调用排序函数就可以了。但必须要注意链表与数组的不同点,链表没有下标,要想访问数据域必须通过节点来访问。

二、代码实现
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;

typedef struct Node
{
	ElemType pData;
	Node* pNext;
}Node,*pList;

void Init(pList* ihead)
{
	*ihead = (pList)malloc(sizeof(Node));
	if (*ihead == NULL)exit(0);
	(*ihead)->pNext = NULL;
	(*ihead)->pData = 0;
}
void Insert(pList head, ElemType val)
{
	pList pCur = head;
	for (int i = 0; i < head->pData; ++i)
	{
		pCur = pCur->pNext;
	}
	pList newNode = (pList)malloc(sizeof(Node));
	newNode->pData = val;
	newNode->pNext = NULL;
	pCur->pNext = newNode;
	head->pData++;
}
void Show(pList head)
{
	pList pCur = head->pNext;
	for (int i = 0; i < head->pData; ++i)
	{
		printf("%d  ", pCur->pData);
		pCur = pCur->pNext;
	}
	printf("\n");
}

void ListSort(pList head)
{
	pList pCur = head->pNext;
	pList pAfter = pCur;
	for (int i = 0; i < head->pData - 1; ++i)
	{
		pCur = head->pNext;
		pAfter = pCur->pNext;
		for (int j = 0; j < head->pData - i-1; ++j)
		{
			if (pAfter->pData < pCur->pData)
			{
				ElemType tmp = pAfter->pData;
				pAfter->pData = pCur->pData;
				pCur->pData = tmp;
			}
			pCur = pCur->pNext;
			pAfter = pAfter->pNext;
		}
	}
}
void Destroy(pList head)
{
	pList pCur = head;//->pNext;
	for(int i=0;i<head->pData-1;i++)
	{
		head->pNext = pCur ->pNext;
		free(pCur);

	}


}

int main()
{
	pList head;
	//Node head;
	Init(&head);
	for (int i = 0; i < 10; ++i)
	{
		Insert(head, rand()%10+1);
	}
	Show(head);
	ListSort(head);
	Show(head);
    Destroy(head);
	return 0;
}

运行结果:




猜你喜欢

转载自blog.csdn.net/lixin_com/article/details/77883674