这道题有没有大佬
原题链接:463.删除数字2023-07-19 20:26:50
发布于:上海
有没有用链表做的大佬呢
全部评论 3
//还真有 #include <iostream> using namespace std; // 定义链表节点结构 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(nullptr) {} }; // 插入节点到链表末尾 void insertAtEnd(ListNode*& head, int value) { ListNode* newNode = new ListNode(value); if (head == nullptr) { head = newNode; } else { ListNode* temp = head; while (temp->next != nullptr) { temp = temp->next; } temp->next = newNode; } } // 删除链表中第一个出现的指定值 void deleteFirstOccurrence(ListNode*& head, int value) { if (head == nullptr) return; if (head->val == value) { ListNode* temp = head; head = head->next; delete temp; return; } ListNode* current = head; while (current->next != nullptr &¤t->next->val != value) { current = current->next; } if (current->next != nullptr) { ListNode* temp = current->next; current->next = current->next->next; delete temp; } } // 打印链表 void printList(ListNode* head) { ListNode* temp = head; while (temp != nullptr) { cout << temp->val << " "; temp = temp->next; } cout << endl; } int main() { int n; cin >> n; ListNode* head = nullptr; for (int i = 0; i < n; i++) { int value; cin >> value; insertAtEnd(head, value); } int m; cin >> m; deleteFirstOccurrence(head, m); printList(head); // 释放链表内存 while (head != nullptr) { ListNode* temp = head; head = head->next; delete temp; } return 0; }
2024-11-24 来自 浙江
0转人工
2024-11-25 来自 广东
0
其实很简单啊
2024-01-22 来自 广东
06
2024-01-21 来自 广东
0
有帮助,赞一个