#include <iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode *prev, *next;
    ListNode(int x) : val(x), prev(NULL), next(NULL) {}
};

ListNode *createList() {
    ListNode *head = new ListNode(-1);  // 头节点
    ListNode *tail = head;  // 尾指针
    int val;
    while (cin >> val && val != -1) {
        ListNode *node = new ListNode(val);
        tail->next = node;
        node->prev = tail;
        tail = node;
    }
    tail->next = head->next;  // 链接首尾节点
    head->next->prev = tail;
    return head->next;  // 返回首节点
}

void deleteNode(ListNode *head, int x) {
    ListNode *cur = head;
    bool exist = false;  // 标记x是否存在
    do {
        if (cur->val == x) {
            exist = true;
            ListNode *p = cur->prev, *q = cur->next;
            p->next = q;
            q->prev = p;
            delete cur;
        }
        cur = cur->next;
    } while (cur != head);
    if (!exist) cout << -1 << endl;
}

void printList(ListNode *head) {
    ListNode *cur = head;
    while (cur->next != head) {
        cout << cur->val << ' ';
        cur = cur->next;
    }
    cout << cur->val << endl;
}

int main() {
    ListNode *head = createList();
    int x;
    while (cin >> x && x != -1) {
        deleteNode(head, x);
    }
    printList(head);
    return 0;
}
C++ 环形双向链表删除操作实现

原文地址: https://www.cveoy.top/t/topic/lHEQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录