题解 | #从单向链表中删除指定值的节点# 构造,删除,打印
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream> using namespace std; struct ListNode { ListNode* next; int val; ListNode() : val(0), next(nullptr) {} ListNode(int value) : val(value), next(nullptr) {} ListNode(ListNode* next) : val(0), next(next) {} ListNode(ListNode* next, int value) : val(value), next(next) {} }; int main() { int num; // 输入个数 cin >> num; ListNode* head = nullptr; while (num--) { // 构造头节点 if (!head) { int headVal; cin >> headVal; head = new ListNode(headVal); continue; } int first, second; cin >> first >> second; // second值和链表中相等,将first插入到该链表后 auto* p = new ListNode(first); auto* q = head; while (q) { if (q->val == second) { auto* tmp = q->next; q->next = p; p->next = tmp; break; } q = q->next; } } int delVal; // 待删除节点值 cin >> delVal; ListNode dummy; dummy.next = head; auto* pre = &dummy; while (head) { if (head->val == delVal) { pre->next = head->next; break; } head = head->next; pre = pre->next; } head = dummy.next; while (head) { cout << head->val << " "; head = head->next; } return 0; } // 64 位输出请用 printf("%lld")