C++练习题:【问题描述】输入n(n>1)个正整数,每次将输入的整数插入到链表头部。-1表示输入结束。再输入一个正整数,在链表中查找该数据并删除对应的节点。要求输出进行删除操作后链表中所有节点的值。

【问题描述】
输入n(n>1)个正整数,每次将输入的整数插入到链表头部。-1表示输入结束。再输入一个正整数,在链表中查找该数据并删除对应的节点。要求输出进行删除操作后链表中所有节点的值。
【输入形式】
输入以空格分隔的n个整数,以-1结束输入,再输入一个要删除的整数。

【输出形式】
从链表第一个元素开始,输出链表中所有的节点值。以空格分隔。

【样例输入】
2 4 6 7 8 4 -1
2
【样例输出】
4 8 7 6 4
【样例说明】
输入以空格分隔的n个整数2 4 6 7 8 4, 以-1结束输入
然后输入2,删除2之后输出剩余整数。

#include <iostream>

struct Node {
    int data;
    Node* next;
};

Node* insertNode(Node* head, int value) {
    Node* newNode = new Node;
    newNode->data = value;
    newNode->next = head;
    return newNode;
}

Node* deleteNode(Node* head, int value) {
    Node* current = head;
    Node* previous = nullptr;

    // 找到待删除节点
    while (current != nullptr) {
        if (current->data == value) {
            break;
        }
        previous = current;
        current = current->next;
    }

    // 若找到了待删除节点
    if (current != nullptr) {
        // 若待删除节点是头节点
        if (previous == nullptr) {
            head = head->next;
        } else {
            previous->next = current->next;
        }
        delete current;
    }

    return head;
}

void printList(Node* head) {
    Node* current = head;
    while (current != nullptr) {
        std::cout << current->data << " ";
        current = current->next;
    }
    std::cout << std::endl;
}

int main() {
    Node* head = nullptr;
    int num;

    // 输入n(n>1)个正整数,将其插入链表头部
    while (true) {
        std::cin >> num;
        if (num == -1) {
            break;
        }
        head = insertNode(head, num);
    }

    // 输入要删除的正整数
    int deleteNum;
    std::cin >> deleteNum;

    // 在链表中查找并删除对应的节点
    head = deleteNode(head, deleteNum);

    // 输出链表中所有节点的值
    printList(head);

    // 释放链表空间
    Node* current = head;
    while (current != nullptr) {
        Node* temp = current;
        current = current->next;
        delete temp;
    }

    return 0;
}

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值