实现功能:
- 单链表的创建
- 单链表的插入(头插法、尾插法)
- 单链表的删除
- 单链表的遍历
- 单链表的排序
代码实现:
/*有头节点的单链表*/
#include <stdio.h>
#include <stdlib.h>
//定义链表节点的结构体
typedef struct node_st
{
int data;
struct node_st *next;
}list;
/*函数声明部分*/
list *list_create(); //链表创建
void list_insert_h(list *head,int data);//头插法
void list_insert_t(list *head,int data);//尾插法
int list_delete(list *head,int data); //链表删除
void list_print(list *head); //链表遍历
void list_sort(list *head); //单链表的排序
int main()
{
list *head = list_create();
//单链表的插入
list_insert_h(head,1);
list_insert_h(head,3);
list_insert_h(head,2);
list_insert_t(head,4);
list_insert_t(head,4);
list_print(head);
//单链表的排序
list_sort(head);
list_print(head);
//单链表的删除
if(list_delete(head,3))
{
printf("删除成功\n");
}
else
{
printf("删除失败\n");
}
list_print(head);
return 0;
}
/*函数实现部分*/
//创建只有头节点的空链表
//返回线性链表的头指针
list *list_create()
{
list *head = malloc(sizeof(list));//申请内存空间
head->data = 0; //存放有效节点的个数
head->next = NULL;
return head; //返回头指针
}
//头部插入(head):插在头节点的后面
//参数1:线性链表的头指针
//参数2:你想要插入的数据
void list_insert_h(list *head,int data)
{
list *new = malloc(sizeof(list));
new->data = data; //新节点的数据域
new->next = head->next;//new,head指向同1个后继
head->next = new; //new插在头节点后面
head->data++; //有效节点的个数加1
}
//尾部插入(tail):插在尾节点后面
//参数1:线性链表的头指针
//参数2:你想要插入的数据
void list_insert_t(list *head,int data)
{
//为新节点申请内存空间,大小是list结构体
list *new = malloc(sizeof(list));
new->data = data; //新节点的数据域
list *node = head; //尾节点
int i = 0;
//循环找到最后一个节点node
for(i=0;i<head->data;i++)
{
node = node->next;
}
new->next = NULL; //新节点的指针域/node->next
node->next = new; //new插在尾节点后面
head->data ++; //有效节点个数加1
}
//删除节点
//参数1:线性链表的头指针
//参数2:你想要删除的数据
//返回成功的标志
int list_delete(list *head,int data)
{
list *pre_node = head; //前驱节点
list *node = head->next; //当前节点
while(node) //若当前节点不为空
{
if(node->data==data) //判断节点的数据
{
//要删除node节点:node的前驱指向后继,跳过node
pre_node->next = node->next;
free(node); //释放内存
head->data--; //有效节点减1
return 1; //删除成功
}
//继续往下找
pre_node = node;
node = node->next;
}
return 0; //删除失败
}
//打印线性链表
//参数1:线性链表的头指针
void list_print(list *head)
{
//从第1个有效节点开始,头节点的数据域不要
list *node = head->next;
while(node) //若节点不为空
{
printf("%d->",node->data);
node = node->next;
}
printf("NULL\n");
}
//单链表的排序,冒泡排序:从小到大
void list_sort(list *head)
{
int i,j,tmp;
list *node1,*node2,*node3;
for(i=0;i<head->data-1;i++)//排序的趟数
{
node1 = head->next; //第1个有效节点,每排完一趟需从头再排
for(j=0;j<head->data-1-i;j++)//每排完一趟,下次需要排的元素个数-1
{
node2 = node1; //当前比较的相邻节点
node3 = node1->next;
if(node2->data > node3->data)//相邻两个节点比较,大于就交换数据域
{
tmp = node2-> data;
node2->data = node3->data;
node3->data = tmp;
}
node1 = node1->next; //下个节点继续循环比较
}
}
}
运行结果: