自己保存一下,建立鏈表的程序,省的以后每次建立鏈表的時候,還需要重新在寫。
通過下面的代碼,建立的鏈表節點數為10,每個節點保存的數為其下標即:0-9
這里要注意一點,在void createList(ListNode* &pHead)的時候,用的是指針引用,因為在main中head並沒有開辟空間,如果在createList中為pHead開辟空間的時候,main中的head依舊還是指向NULL的。
如果在main中為head開辟了空間的話,就不需要用指針的引用了。道理很簡單,就和你傳int參數是一個道理。createList中的pHead是形參,也就是說pHead的地址和main中head的地址是不一樣的,如果在main中為head開辟了空間的話,那么pHead
和head所保存的地址是一樣的。后面就用了第二種方法實現。
#include "stdafx.h" #include <iostream> #include<cstring> #include <vector> #include <assert.h> using namespace std; struct ListNode { int m_key; ListNode* next; }; void createList(ListNode* &pHead) { pHead = new ListNode; pHead->m_key= 0; pHead->next = NULL; ListNode* p = pHead; for(int i=1; i<10; i++) { ListNode* pNewNode = new ListNode; pNewNode->m_key = i; pNewNode->next = NULL; p->next = pNewNode; p = pNewNode; } } void destoryList(ListNode* pHead) { assert(pHead!=NULL); ListNode* pNext = pHead->next; while(pNext != NULL) { delete pHead; pHead = pNext; pNext = pHead->next; } delete pHead; pHead = NULL; return; } int main() { ListNode* head = NULL; createList(head); destoryList(head); }
void createList1(ListNode* pHead) { ListNode* p = pHead; for(int i=1; i<10; i++) { ListNode* pNewNode = new ListNode; pNewNode->m_key = i; pNewNode->next = NULL; p->next = pNewNode; p = pNewNode; } } void destoryList(ListNode* pHead) { assert(pHead!=NULL); ListNode* pNext = pHead->next; while(pNext != NULL) { delete pHead; pHead = pNext; pNext = pHead->next; } delete pHead; pHead = NULL; return; } int main() { ListNode* head = NULL; //createList(head); head = new ListNode; head->m_key =0; head->next = NULL; createList1(head); destoryList(head); }
兩者的效果是一樣的。