/*
链表基本操作:
插入节点和删除节点
*/
/*
思路:
使用指向链表的头指针,这样在新插入节点后,头指针不会改变
*/
struct ListNode{
int value;
ListNode* next;
}
void AddToTail(ListNode** pHead,int value){
if(pHead == null){
return;
}
//新建节点
ListNode *pNew = new ListNode();
pNew->value = value;
pNew->next = null;
//当为空链表时
if(\*pHead == null){
\*pHead = pNew;
}else{
//遍历到链表的最后一个节点
ListNode \*pNode = \*pHead;
while(pNode->next != null){
pNode = pNode->next;
}
pNode->next = pNew;
}
}
void RemoveNode(ListNode** pHead,int value){
if(pHead == null || *pHead == null){
return;
}
ListNode* toBeDeleted = null;
ListNode* pNode = pHead;
if((\*pHead)->value == value){
toBeDeleted = \*pHead;
pHead = toBeDeleted;
}else{
while(pNode->next != null && pNode->next->value != value){
pNode = pNode->next;
}
if(pNode->next != null && pNode->next->value == value){
toBeDeleted = pNode->next;
pNode->next = pNode->next->next;
}
}
if(toBeDeleted != null){
delete(toBeDeleted);
toBeDeleted = null;
}
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章