题解 | #从单向链表中删除指定值的节点#

从单向链表中删除指定值的节点

http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f

自定义一个链表节点类之后通过增删节点操作实现功能,参考代码注释:

using namespace std;

class ListNode {
  public:
    int val;
    ListNode* next;
    ListNode(int n): val(n), next(nullptr) {}
};

int main() {
    int nodeNum = 0;
    int firstVal = 0;
    cin >> nodeNum >> firstVal;
    ListNode *dummy = new ListNode(0);
    dummy->next = new ListNode(firstVal);
    nodeNum--;
    // 对从第三个数字开始的每一对数字进行操作,构造节点,添加元素
    while (nodeNum--) {
        int left, right;
        cin >> right >> left;
        ListNode *curr = dummy->next;
        while (curr != nullptr) {
            if (curr->val == left) {
                ListNode* add = new ListNode(right);
                ListNode* tmp = curr->next;
                curr->next = add;
                add->next = tmp;
                break;
            }
            curr = curr->next;
        }
    }
    // 读取需要删除的元素的值,遍历链表删除
    int toDelete = 0;
    cin >> toDelete;
    ListNode *curr = dummy;
    while (curr->next != nullptr) {
        if (curr->next->val == toDelete) {
            curr->next = curr->next->next;
            break;
        }
        curr = curr->next;
    }
    // 打印结果
    curr = dummy->next;
    while (curr != nullptr) {
        cout << curr->val << ' ';
        curr = curr->next;
    }
    cout << endl;
    return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
6 收藏 评论
分享
牛客网
牛客企业服务