指標與鍊錶

2021-09-25 01:18:18 字數 2181 閱讀 3647

真正有用的動態變數很少會是int,double這樣的簡單型別.相反都是一些複雜型別,比如陣列,結構體,或類.結構體或類型別的動態變數通常由乙個或多個成員變數,這些變數是指標,可將動態變數連線到其它動態變數.

一.節點

在c++中,節點作為結構或類實現.

struct listnode

typedef listnode* listnodeptr;

c++支援箭頭操作符:head->count=1;替代了由圓點操作符和提領操作符組成的(*head).count=2;c++11引入nullptr.避免因為null實際是數字0的造成歧義.

#include #include #include #include using namespace std;

void func(int *p)

2.遍歷

while(head->link!=null)//普通遍歷 		

// for(iter=head;iter->link!=null;iter=iter->link)//迭代器遍歷

//

4.刪除節點

void del(listnodeptr &head,int discardtarget)

if(pb->count==discardtarget)

else//找到的節點是普通節點

free(pb);

} else cout<5.搜尋節點

listnodeptr search(listnodeptr head,int target)

if(here->count==target) return here;

else return null;

} }

完整**如下:

#include #include #include #include using namespace std;

struct listnode

;typedef listnode* listnodeptr;

void headinsert(listnodeptr& head,int c,string i)

void insert(listnodeptr afterme,int c,string i)

void del(listnodeptr &head,int discardtarget)

if(pb->count==discardtarget)

else//找到的節點是普通節點

free(pb);

} else cout

if(here->count==target) return here;

else return null;

} }int main(int argc, char** ar**)

// for(iter=head;iter->link!=null;iter=iter->link)//迭代器遍歷

2.二叉樹

名為root的指標指向根節點(頂部節點).根節點的作用類似於普通鍊錶的表頭節點.跟隨連線,可以到達樹中的任何節點.

在分支結束的節點中,兩個連線變數均設為空,這些節點稱為葉節點.

二叉樹能夠高效儲存和檢索資料.

四.類構成的鍊錶(node類)

前面建立鍊錶時,是用struct容納節點內容,同樣地資料結構還有類,基本原理一樣.

node類的介面檔案

//標頭檔案node.h,類構成的鍊錶 

namespace linkedlistofclasses

typedef node* nodeptr;

};

指標與鍊錶

指標是乙個儲存計算機記憶體位址的變數。從指標指向的記憶體讀取資料稱作指標的取值。指標可以指向某些具體型別的變數位址,例如int long和double。指標也可以是void型別 null指標和未初始化指標。根據出現的位置不同,操作符 既可以用來宣告乙個指標變數,也可以用作指標的取值。當用在宣告乙個變...

鍊錶與快慢指標

之前刷劍指offer遇到尋找鍊錶環的入口節點,需要使用到快慢指標,然後題一變,發現自己總是不能立馬聯想起來。總結一下快慢指標法在鍊錶中的一些常見的用處。leetcode 141 快指標每次走2步,慢指標每次走1步,如果鍊錶中有環,則兩個指標就會相遇。public boolean hascycle l...

Leetcode 快慢指標與鍊錶

1.給定乙個鍊錶,判斷鍊錶中是否有環。解釋 鍊錶中有乙個環,其尾部連線到第二個節點。ps 從例子中根本看不出來好嘛。自己理解就ok 經典思想,快慢指標,如果有環存在,快指標總會追上慢指標 python definition for singly linked list.class listnode ...