[数据结构]_[C/C++]_[链表的最佳创建方式]
2016-10-22 00:51
363 查看
场景
1.链表在C/C++里使用非常频繁, 因为它非常使用, 可作为天然的可变数组. push到末尾时对前面的链表项不影响. 反观C数组和std::vector, 一个是静态大小, 一个是增加多了会对之前的元素进行复制改写(线程非常不安全).2.通常创建链表都是有next这样的成员变量指向下一个项, 通过定义一个head,last来进行链表创建. 参考函数 TestLinkCreateStupid().
说明
1.其实很早就知道另一种创建方式, 但是一直没总结. 没见过的童鞋看看以下创建链表的方式你用了哪一种. linus说了不会第一种的TestLinkCreateClever()根本不会用指针(看来我真不会用指针). 这种方式在循环里根本不用判断, 可见效率有多高.// test_shared.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <memory> #include <string> #include <iostream> typedef struct stage_tag { int data_ready; /* Data present */ long data; /* Data to process */ struct stage_tag *next; /* Next stage */ } stage_t; // 高效率的链表创建方式 stage_t* TestLinkCreateClever(int stages) { stage_t *head = NULL,*new_stage = NULL,*tail = NULL; stage_t **link = &head; // 区别在这个指针地址变量上,它起到绑定新的stage的作用. for(int i =0; i<stages;++i) { new_stage = (stage_t*)malloc(sizeof(stage_t)); new_stage->data_ready = 0; new_stage->data = i; *link = new_stage; // 把新的stage赋值给link指向的指针地址 link = &new_stage->next; // 绑定下一个的指针地址 } tail = new_stage; *link = NULL; return head; } // 低效率的链表创建方式 stage_t* TestLinkCreateStupid(int stages) { stage_t *head = NULL,*new_stage = NULL,*tail = NULL; for(int i =0; i<stages;++i) { new_stage = (stage_t*)malloc(sizeof(stage_t)); new_stage->data_ready = 0; new_stage->data = i; new_stage->next = NULL; if(tail) tail->next = new_stage; else head = new_stage; tail = new_stage; } return head; } int _tmain(int argc, _TCHAR* argv[]) { std::cout << "=== TestLinkCreateClever ===" << std::endl; auto first = TestLinkCreateClever(10); while(first) { std::cout << "data: " << first->data << std::endl; first = first->next; } std::cout << "=== TestLinkCreateStupid ===" << std::endl; auto second = TestLinkCreateStupid(10); while(second) { std::cout << "data: " << second->data << std::endl; second = second->next; } return 0; }
参考
Programming with POSIX Threads相关文章推荐
- [数据结构]_[C/C++]_[链表的最佳创建方式]
- [C++]数据结构:链表二叉树的创建与四种遍历方式
- 【数据结构 笔记00】C++链表的创建与操作
- C++数据结构---链表(链表节点创建)
- C++数据结构---链表(链表创建)
- 数据结构学习系类列十-链表集合(c++)
- c++创建对象的两种方式
- C++数据结构------顺序表和链表
- 关于单链表的各种函数的C++源代码,创建单链表、求表长、插入、删除等等
- 面向对象c++数据结构--基本数据结构之链表(连载中……)(凌风)
- C++两种方式创建对象(new和申明)
- 数据结构学习系列三-单向循环链表(c++实现且应用模板)
- 数据结构 链表的lua实现 仿照C++中list 实现
- C/C++版数据结构之链表<二>
- 数据结构_队列_用链表动态建立释放节点实现队列各种操作_C++实现
- 算法与数据结构课程中的c++实现的顺序表和链表
- C++数据结构--链表
- 数据结构-C++描述:动态创建和释放一个二维数组
- [数据结构]链表创建、打印、反转
- C++链表的创建与操作