目录
定义单链
struct ListNode {
int val;
ListNode* next;
ListNode(int value) :val(value), next(nullptr) {
}
};
1. 向单链表尾部插入元素
ListNode* insertTail(ListNode* pHead, int x) {
if (pHead == nullptr) return new ListNode(x);
ListNode* pNode = pHead;
while (pNode->next != nullptr)
pNode = pNode->next;
pNode->next = new ListNode(x);
return pHead;
}
2. 删除单链表中第一个值为x的节点
ListNode* deleteFirstTarget(ListNode* pHead, int x) {
if (pHead == nullptr) return pHead;
if (pHead->val == x) return pHead->next;
ListNode* pPre = pHead;
ListNode* pNode = pHead->next;
while (pNode != nullptr && pNode->val != x) {
pPre = pNode;
pNode = pNode->next;
}
if (pNode != nullptr) pPre->next = pNode->next;
return pHead;
}
3. 删除单链表中的目标节点
void deleteTargetNode(ListNode** pHead, ListNode* pTarget) {
if (pHead==nullptr || *pHead == nullptr) return;
if (pTarget->next != nullptr) {
ListNode* pNext = pTarget->next;
pTa