Skip to main content Link Menu Expand (external link) Document Search Copy Copied

CS162 - 3B

TABLE OF CONTENTS

Problem

  1. Delete the first Node
    void deleteAtBeginning(Node* &pHead);
    
  2. Delete the first Node with value k from the list
    void deleteANode(Node*& pHead, int k);
    
  3. Delete all nodes k from the list
    void deleteAllNode(Node*& pHead, int k);
    

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
void deleteAtBeginning(Node* &pHead)
{
    Node* cur = pHead;
    if (pHead) pHead = pHead->pNext;
    delete cur;
}

void deleteANode(Node*& pHead, int k)
{
    if(pHead != nullptr && pHead->data == k) {
        deleteAt(pHead);
        return;
    }

    Node* tmp = nullptr;
    Node* cur = pHead;
    while(cur != nullptr && cur->data != k) {
        tmp = cur;
        cur = cur->pNext;
    }
    if (cur == nullptr) return;
    tmp->pNext = cur->pNext;
    delete cur;
}

void deleteAllNode(Node*& pHead, int k)
{
    while (pHead != nullptr && pHead->data == k) deleteAt(pHead);
    if (pHead == nullptr) return;
    for (Node *cur = pHead; cur->pNext != nullptr; ) {
        if(cur->pNext->data == k)
            deleteAt(cur->pNext);
        else
            cur = cur->pNext;
    }
}