c语言实现基本的数据结构(二) 链表(包括链表的三种简单排序算法)

#include "stdafx.h"
#include <stdlib.h>
//创建一个节点,data为value,指向NULL
Node* Create(int value){
Node* head = (Node*)malloc(sizeof(Node));
head->data = value;
head->next = NULL;
return head;
}
//销毁链表
bool Destroy_List(Node* head){
Node* temp;
while (head){
temp = head->next;
free(head);
head = temp;
}
head = NULL;
return true;
}
//表后添加一个节点,Create(value)
bool Append(Node* head,int value){
Node* n = Create(value);
Node* temp = head;
while (temp->next){
temp = temp->next;
}
temp->next = n;
return ;
}
//打印链表
void Print_List(Node* head){
Node* temp = head->next;
while (temp){
printf("%d->", temp->data);
temp = temp->next;
}
printf("\n");
}
//在链表的第locate个节点后(头节点为0)插入创建的节点Create(value)
bool Insert_List(Node* head, int locate, int value){
Node* temp = head;
Node* p;
Node* n = Create(value);
if (locate < )
return false;
while (locate--){
if (temp->next == NULL){
temp->next = Create(value);
return true;
}
temp = temp->next;
}
p = temp->next;
temp->next = n;
n->next = p;
return true;
}
//删除第locate个节点后(头节点为0)的节点
bool Delete_List(Node* head, int locate){
Node* temp = head;
Node* p;
if (locate < )
return false;
while (locate--){
if (temp == NULL){
return false;
}
temp = temp->next;
}
p = temp->next->next;
free(temp->next);
temp->next = NULL;
temp->next = p;
return true;
}
//获取链表长度(不包括头节点)
int Size_List(Node* head){
Node* temp = head;
int size = ;
while (temp->next){
temp = temp->next;
size++;
}
return size;
}
//链表的三种排序(选择,插入,冒泡)
bool Sort_List(Node* head){
int t = ;
int size = Size_List(head);
//选择排序
/*for (Node* temp = head->next; temp != NULL; temp = temp->next){
for (Node* p = temp; p != NULL; p = p->next){
if (temp->data > p->data){
printf("换%d和%d\n", temp->data, p->data);
t = temp->data;
temp->data = p->data;
p->data = t;
}
}
}*/
//插入排序
/*for (Node* temp = head->next->next; temp != NULL; temp = temp->next){
for (Node* p = head; p->next != NULL; p = p->next){
if (p->next->data > temp->data)
{
printf("换%d和%d\n", temp->data, p->next->data);
t = temp->data;
temp->data = p->next->data;
p->next->data = t;
}
}
}*/
//冒泡排序
for (Node* temp = head->next; temp->next != NULL; temp = temp->next){
for (Node* p = head->next; p->next != NULL; p = p->next){
if (p->data > p->next->data){
t = p->data;
p->data = p->next->data;
p->next->data = t;
}
}
}
return ;
}
上一篇:<算法基础><排序>三种高级排序——快速排序,堆排序,归并排序


下一篇:三种排序算法python源码——冒泡排序、插入排序、选择排序