HJ48 从单向链表中删除指定值的节点 (链表需要用class来写,构造函数要写,初始化的是有*号表示这是指针)

#include 
using namespace std;

// define the ListNode class
class ListNode {
public:
    int value; // the value of the node
    ListNode* next; // the pointer to the next node
    // constructor to initialize the node
    ListNode(int val) {
        value = val;
        next = nullptr;
    }
};

int main() {
    int length;
    cin >> length;
    int headValue;
    cin >> headValue;
    // create the head node using the class constructor
    ListNode *head = new ListNode(headValue);
    // create a dummy head node that points to the head node
    ListNode *dummy = new ListNode(0);
    dummy->next = head;
    length--;
    while (length--) {
        int curV;
        int nextV;
        cin >> nextV >> curV;
        // find the node with curV using the dummy head
        ListNode *cur = dummy;
        while (cur->next != nullptr && cur->next->value != curV) {
            cur = cur->next;
        }
        // insert a new node with nextV after cur
        ListNode *temp = new ListNode(nextV);
        temp->next = cur->next;
        cur->next = temp;
    }
    // delete the node with toDel using the dummy head
    int toDel;
    cin >> toDel;
    ListNode *cur = dummy;
    while (cur->next != nullptr) {
        if (cur->next->value == toDel) {
            // delete the node by skipping it
            cur->next = cur->next->next;
        } else {
            // move to the next node
            cur = cur->next;
        }
    }
    // print the list values using the head node
    head = dummy->next; // skip the dummy head
    while (head != nullptr) {
        cout << head->value << " ";
        head = head->next;
    }
}

你可能感兴趣的:(链表,算法,数据结构)