其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
如何使用比较常见的动态数据结构

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

指针和结构
结构可以包含指针,当然也可以是一个指向同一结构其他实例的指针:
例如:
struct node
{
        struct node *next_ptr;
        int value;
}
仔细思考一下,现在我们发现,如果我们可以动态创建 node ,那我们在内存中可以保存的数据就可以达到无限大。所以我们需要的是一个这样的程序,当用户说“我想要一个新节点”时,程序就可以创建它。当然不能用光内存。
因此我们可以创建如下程序:
#include <stdio.h>

struct node
{
        struct node *next_ptr;
        int value;
};

struct node *first_ptr;

void add_list(int item)
{
        struct node *new_item_ptr = malloc(sizeof(struct node));
        (*new_item_ptr).value = item;
        (*new_item_ptr).next_ptr = first_ptr;
        first_ptr = new_item_ptr;
}

int main()
{
        int j = 0;
        int i = j;
        struct node *current_ptr;
        scanf("%d", &i);
        for(; j<=i; j++) add_list(j);
        current_ptr = first_ptr;
        while(current_ptr != NULL)
        {
                printf("%d\n", (*current_ptr).value);
                first_ptr = (*first_ptr).next_ptr;
                free(current_ptr);
                current_ptr = NULL;
                current_ptr = first_ptr;
        }
        current_ptr = first_ptr;
        return 0;
}

摘自:辣妹子社区-C/C++论坛




相关文章

相关软件