1. 程式人生 > >C++建立及銷燬連結串列

C++建立及銷燬連結串列

 struct ListNode {
	 int val;
	 ListNode *next;
	 ListNode(int x) : val(x), next(NULL) {}
 };

 void createList(ListNode* &pHead){
	 pHead = new ListNode(-1);
	 int length = 5;
	 ListNode *p = pHead;
	 for (size_t i = 0; i < length; i++)
	 {
		 ListNode *node = new ListNode(i);

		 p->next = node;
		 p = node;
	 }		
 }

 void destroyList(ListNode* pHead){
	 _ASSERT(pHead != NULL);

	 ListNode *pNext = pHead->next;
	 while (pNext!=NULL)
	 {
		 delete pHead;
		 pHead = pNext;
		 pNext = pHead->next;
	 };

	 delete pHead;
	 pHead = NULL;

	 


 }