List_insert

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;
}

 

 

mooc地址

 


 

Tips:

malloc()和free()的基本概念以及基本用法:

函数原型及说明:

void *malloc(long NumBytes):该函数分配了NumBytes个字节,并返回了指向这块内存的指针。如果分配失败,则返回一个空指针(NULL)。

关于分配失败的原因,应该有多种,比如说空间不足就是一种。

void free(void *FirstByte): 该函数是将之前用malloc分配的空间还给程序或者是操作系统,也就是释放了这块内存,让它重新得到自由。

转载于:https://www.cnblogs.com/ruruozhenhao/p/7931199.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值