zoukankan      html  css  js  c++  java
  • 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!
    ");
        else
        {
            current = Head;
    
            while( current != NULL )
            {
                printf("%d ", current->key);
                current = current->next;
            }
    
            printf("
    ");
        }
    }
    
    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分配的空间还给程序或者是操作系统,也就是释放了这块内存,让它重新得到自由。

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    如何隔離物件之間的相依性
    Replace Temp with Query
    Replace conditional with Polymorphism
    Switch to strategy
    Microsoft Visual Studio 插件
    Windows Phone 8 开发系列(持续更新中)
    Windows Phone 如何振动手机?
    Windows Phone 如何在程序中播放提示声音?
    实现一个纵向排列的 ListBox ,并具有操作按钮
    多个 App 间启动
  • 原文地址:https://www.cnblogs.com/h-hkai/p/7931199.html
Copyright © 2011-2022 走看看