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分配的空间还给程序或者是操作系统,也就是释放了这块内存,让它重新得到自由。