C++數(shù)據(jù)結(jié)構(gòu)之鏈表的創(chuàng)建
C++數(shù)據(jù)結(jié)構(gòu)之鏈表的創(chuàng)建
前言
1.鏈表在C/C++里使用非常頻繁, 因?yàn)樗浅J褂? 可作為天然的可變數(shù)組. push到末尾時(shí)對前面的鏈表項(xiàng)不影響. 反觀C數(shù)組和std::vector, 一個(gè)是靜態(tài)大小, 一個(gè)是增加多了會對之前的元素進(jìn)行復(fù)制改寫(線程非常不安全).
2.通常創(chuàng)建鏈表都是有next這樣的成員變量指向下一個(gè)項(xiàng), 通過定義一個(gè)head,last來進(jìn)行鏈表創(chuàng)建. 參考函數(shù) TestLinkCreateStupid().
說明
1.其實(shí)很早就知道另一種創(chuàng)建方式, 但是一直沒總結(jié). 沒見過的童鞋看看以下創(chuàng)建鏈表的方式你用了哪一種. linus說了不會第一種的TestLinkCreateClever()根本不會用指針(看來我真不會用指針). 這種方式在循環(huán)里根本不用判斷, 可見效率有多高.
// test_shared.cpp : 定義控制臺應(yīng)用程序的入口點(diǎn)。
//
#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;
// 高效率的鏈表創(chuàng)建方式
stage_t* TestLinkCreateClever(int stages)
{
stage_t *head = NULL,*new_stage = NULL,*tail = NULL;
stage_t **link = &head; // 區(qū)別在這個(gè)指針地址變量上,它起到綁定新的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; // 綁定下一個(gè)的指針地址
}
tail = new_stage;
*link = NULL;
return head;
}
// 低效率的鏈表創(chuàng)建方式
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;
}
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C語言 完整游戲項(xiàng)目坦克大戰(zhàn)詳細(xì)代碼
《坦克大戰(zhàn)》以二戰(zhàn)坦克為題材,既保留了射擊類游戲的操作性,也改進(jìn)了射擊類游戲太過于復(fù)雜難玩的高門檻特點(diǎn),集休閑與競技于一身。經(jīng)典再度襲來,流暢的畫面,瘋狂的戰(zhàn)斗,讓玩家再次進(jìn)入瘋狂坦克的世界。玩家的目標(biāo)是控制坦克躲避危險(xiǎn),消滅掉所有的敵人即可進(jìn)入下一關(guān)2021-11-11
C++ 非遞歸實(shí)現(xiàn)二叉樹的前中后序遍歷
本文將結(jié)合動畫和代碼演示如何通過C++ 非遞歸實(shí)現(xiàn)二叉樹的前中后序的遍歷,代碼具有一定的價(jià)值,感興趣的同學(xué)可以學(xué)習(xí)一下2021-11-11
C++實(shí)現(xiàn)高校人員信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)高校人員信息管理系統(tǒng)項(xiàng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-06-06

