题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <iostream> #include <memory> using namespace std; struct ListNode { public: int value; shared_ptr<ListNode> next; ListNode() :value(-1), next(nullptr) {} ListNode(int i) : value(i), next(nullptr) {} }; void insertANumber(shared_ptr<ListNode> head, int value, int point_value) { auto newNode = make_shared<ListNode>(value); while (head!=nullptr) { if (head->value == point_value) { auto temp = make_shared<ListNode>(); temp->next = head->next; head->next = newNode; newNode->next = temp->next; break; } else { head = head->next; } } } int deleteNumber(shared_ptr<ListNode> head, int value) { shared_ptr<ListNode> last; while (head != nullptr) { if (head->value == value) { if (last != nullptr) { last->next = head->next; break; } else { return -1; } } else { last = head; head = head->next; } } return 0; } int main() { int N; int headvalue; cin>>N>>headvalue; shared_ptr<ListNode> head = make_shared<ListNode>(headvalue); for(int i = 0;i!=N-1;++i) { int value,point_value; cin>>value>>point_value; insertANumber(head, value, point_value); } cin>>headvalue; if(deleteNumber(head, headvalue)==-1) head = head->next; while(head!=nullptr) { cout<<head->value<<" "; head = head->next; } } // 64 位输出请用 printf("%lld")
最好使用shared_ptr来分配和管理内存。