List_insert
2024-08-31 16:01:56
List_insert
/* Sorting from little to large use List */
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free */ struct node
{
int key;
struct node *next;
}; typedef struct node Node; Node *Head = NULL;
Node *current; void Insert(int k)
{
Node *new_node; new_node = (Node *)malloc(sizeof(Node));//It is important but i can't understand now new_node->key = k; /* new node is inserted at the begining of the list*/ if ( Head == NULL || Head->key > k )
{
new_node->next = Head;
Head = new_node;
} /* new node is inserted somewhere inside the list */
else
{
current = Head; /* Check what is the value in the next node , after the current node */
/* if it is larger, or if the next node not exist */
/* then we shuold insert the node to next current */
/* else, update current to point to next node */ while(1)
{
if( current->next == NULL || current->next->key > k )
{
new_node->next = current->next;
current->next = new_node;
break;
}
else
current = current->next;
}
}
} void Print()
{
if( Head == NULL )
printf("The list is empty!\n");
else
{
current = Head; while( current != NULL )
{
printf("%d ", current->key);
current = current->next;
} printf("\n");
}
} int main()
{
Insert(15);
Insert(12);
Insert(5); Print(); return 0;
}
Tips:
malloc()和free()的基本概念以及基本用法:
函数原型及说明:
void *malloc(long NumBytes):该函数分配了NumBytes个字节,并返回了指向这块内存的指针。如果分配失败,则返回一个空指针(NULL)。
关于分配失败的原因,应该有多种,比如说空间不足就是一种。
void free(void *FirstByte): 该函数是将之前用malloc分配的空间还给程序或者是操作系统,也就是释放了这块内存,让它重新得到自由。
最新文章
- IT菜鸟的生存指南(三)流行还是经典
- distinct 与 group by 去重
- jenkins 中 Poll SCM 和 Build periodically 的区别
- JavaWeb学习记录(四)——日期和数字的格式转换
- Hibernate中启用日志
- roscpp源码阅读
- 从python的yield说起
- Memcached应用总结
- for语句应用:乘法表
- winform datagridview 添加行号。
- java小白设计模式之观察者模式
- C# 4.0 的 Visual Studio 2010 示例
- git工具——版本的创建与回退
- Crash 的文明世界
- Spring Boot 2.x 学习专栏
- SQLAlchemy 与 fask-SQLAlchemy 中的多表查询例子
- PHPCMS增加投票选项代码
- Spring Cloud 入门 之 Eureka 篇(一)
- tiny4412的烧录工具minitool安装【学习笔记】
- sphinx使用