华为机试 HJ48题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream> #include <bits/stdc++.h> #include <list> using namespace std; std::list<int>::iterator findByPosVal(std::list<int>& myList, int posVal) { std::list<int>::iterator jter; for (auto iter = myList.begin(); iter != myList.end(); iter++) { if (*iter == posVal) { return iter; } } return jter; } void insertVal(std::list<int>& myList, int posVal, int val) { auto jter = findByPosVal(myList, posVal); if (jter != myList.end()) { myList.insert(jter, val); } } void deleteVal(std::list<int>& myList, int val) { auto jter = findByPosVal(myList, val); if (jter != myList.end()) { myList.erase(jter); } } int main() { int n; list<int> myList; while (cin >> n) { // 注意 while 处理多个 case int firstnode; cin >> firstnode; myList.emplace(myList.begin(), firstnode); int val; int posVal; for (int i = 0; i < n - 1; i++) { cin >> val >> posVal; insertVal(myList, posVal, val); } int target; cin >> target; deleteVal(myList, target); if (myList.size() == 0) { std::cout << "nullptr" << std::endl; return 0; } reverse(myList.begin(), myList.end()); for (auto iter = myList.begin(); iter != myList.end(); iter++) { std::cout << *iter << " "; } std::cout << std::endl; } return 0; }