1. 程式人生 > >劍指offer連結串列新增,刪除元素中傳入的pHead為什麼要是指向頭指標的指標問題

劍指offer連結串列新增,刪除元素中傳入的pHead為什麼要是指向頭指標的指標問題

參考自:https://blog.csdn.net/jmt330/article/details/80166752

https://blog.csdn.net/qq_30483585/article/details/79426910?utm_source=blogxgwz3

#include <iostream>
using namespace std;

struct ListNode
{
	int data;
	ListNode* pnext;
};

void addtotail(ListNode** pHead, int value)
{
	ListNode* pNew = new ListNode();
	pNew->data = value;
	pNew->pnext = NULL;

	if (*pHead == NULL)
	{
		*pHead = pNew;
	}
	else
	{
		ListNode* pNode = *pHead;
		while (pNode->pnext != NULL)
		{
			pNode = pNode->pnext;
		}			
		pNode->pnext = pNew;
	}
}

//void removenode(ListNode** pHead, int value)
//{
//	if (*pHead == NULL)
//		return;
//	ListNode *pNode = *pHead;
//	if (pNode->data == value)
//	{
//		*pHead = pNode->pnext;
//		return;
//	}
//	while (pNode->pnext != NULL) {
//		if (pNode->pnext->data == value) {
//			pNode->pnext = pNode->pnext->pnext;
//			delete pNode->pnext;
//			return;
//		}
//		pNode = pNode->pnext;
//	}
//}
int main()
{
	ListNode* p = NULL;
	addtotail(&p, 1);
	addtotail(&p, 1);
	addtotail(&p, 2);
	addtotail(&p, 3);
	//removenode(&p, 1);
	while (p != NULL)
	{
		cout << p->data << endl;
		p = p->pnext;
	}
	return 0;
}