//1.0单链表排序升序(冒泡排序)
void BubbleSortLinkList(LinkList L)
{
LinkList Tail = NULL;
int flag = 0;
if (L->next == NULL || L == NULL){
return;
}
while (L!=Tail)
{
LinkList Pre = L;
LinkList Cur = Pre->next;
while (Cur != Tail)
{
if (Pre->data>Cur->data)
{
DataType tmp = Pre->data;
Pre->data = Cur->data;
Cur->data = tmp;
flag = 1;
}
Pre = Cur;
Cur = Cur->next;
}
Tail = Pre;
if (flag == 0)
return;
}
}
//test.c
#define _CRT_SECURE_NO_WARNINGS 1
typedef int DataType;
#define NULL 0
#include<stdio.h>
#include<windows.h>
#include<assert.h>
typedef struct Node
{
DataType data;
struct Node*next;
}Node, *LinkList;
void InitList(LinkList *L)
{
*L = (Node*)malloc(sizeof(Node));
if (*L == NULL){
printf("申请内存空间失败");
}
(*L)->next = NULL;
(*L)->data = 1;
}
LinkList BuyNode(DataType data)
{
LinkList NewNode = NULL;
NewNode = (LinkList)malloc(sizeof(Node));
if (NewNode == NULL){
printf("为节点创建空间失败");
}
NewNode->data = data;
NewNode->next = NULL;
return NewNode;
}
void PrintList(LinkList L)
{
LinkList Cur = L;
if (L == NULL){
printf("NULL");
}
while (Cur)
{
printf("%d--->", Cur->data);
Cur = Cur->next;
}
printf("NULL\n");
}
void PushBack(LinkList* L, DataType data)
{
assert(L);
LinkList Cur = *L;
if (Cur == NULL){
Cur = BuyNode(data);
}
while (Cur->next)
{
Cur = Cur->next;
}
Cur->next = BuyNode(data);
}
void PushFront(LinkList* L, DataType data)
{
assert(L);
LinkList Cur = *L;
if (Cur == NULL){
*L = BuyNode(data);
}
*L = BuyNode(data);
(*L)->next = Cur;
}
void PopBack(LinkList*L)
{
LinkList Cur = *L;
LinkList Pre = NULL;
assert(L);
if (Cur->next == NULL || Cur == NULL)
return;
while (Cur->next){
Pre = Cur;
Cur = Cur->next;
}
free(Pre->next);
Pre->next = NULL;
}
void PopFront(LinkList* L)
{
LinkList Cur = *L;
assert(L);
if (Cur->next == NULL || Cur == NULL)
return;
*L = (*L)->next;
free(Cur);
}
//1.0单链表排序升序(冒泡排序)
void BubbleSortLinkList(LinkList L)
{
LinkList Tail = NULL;
int flag = 0;
if (L->next == NULL || L == NULL){
return;
}
while (L!=Tail)
{
LinkList Pre = L;
LinkList Cur = Pre->next;
while (Cur != Tail)
{
if (Pre->data>Cur->data)
{
DataType tmp = Pre->data;
Pre->data = Cur->data;
Cur->data = tmp;
flag = 1;
}
Pre = Cur;
Cur = Cur->next;
}
Tail = Pre;
if (flag == 0)
return;
}
}
void test1()
{
LinkList M = NULL;
InitList(&M);
//PushFront(&M, 0);
PushBack(&M, 3);
PushBack(&M, 2);
/*PushBack(&M, 5);
PushBack(&M, 4);*/
///*PopBack(&M);
//PopFront(&M);
//Erase(&M, Find(&M,3));
//Insert(Find(&M,0), 3);
//printf("%d\n",Size(M));
//
BubbleSortLinkList(M);
PrintList(M);
}
int main()
{
test1();
system("pause");
return 0;
}
单链表排序(冒泡法)
最新推荐文章于 2022-08-10 11:54:40 发布