#include <iostream> using namespace std; struct ListNode { int data; ListNode* next; // 构造函数,data(value), next(nullptr) 是初始化列表; ListNode(int value) : data(value), next(nullptr) {} }; // 定义单向链表类 class SinglyLinkedList { private: ListNode* header; public: SinglyLinkedList(int val) { header = new ListNode(val); } // 在 b 的后面插入 a void insertByElem(int a, int b) { ListNode* current = header; ListNode* newNode = new ListNode(a); while (current != nullptr && current->data != b) { current = current->next; } newNode->next = current->next; current->next = newNode; } // 遍历 链表 void traverse() { ListNode* current = header; while (current != nullptr) { cout << current->data << " "; current = current->next; } cout << endl; } // 删除节点 val void deleteNode(int val) { ListNode* current = header; ListNode* prev = nullptr; while (current != nullptr && current->data != val) { prev = current; current = current->next; } // 没有 该节点 if (current == nullptr) return; // 第一个就是 节点 val 所以 prev没有进入上面的循环 if (prev == nullptr) { header = current->next; } else { // 节点 val 在链表中间; prev->next = current->next; } delete current; } // 析构函数 ~SinglyLinkedList() { ListNode* current = header; ListNode* nextNode; while (current != nullptr) { nextNode = current->next; delete current; current = nextNode; } } }; int main() { int n, head; while (cin >> n >> head) { SinglyLinkedList s(head); int a, b; while (--n) { cin >> a >> b; s.insertByElem(a, b); } int c; cin >> c; s.deleteNode(c); s.traverse(); } return 0; }