题解 | #牛牛的链表删除#
牛牛的链表删除
https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createLinkedList(int arr[], int n) {
if (n == 0) {
return NULL;
}
ListNode* head = new ListNode(arr[0]);
ListNode* curr = head;
for (int i = 1; i < n; i++) {
curr->next = new ListNode(arr[i]);
curr = curr->next;
}
return head;
}
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* prev = dummy;
ListNode* curr = head;
while (curr != NULL) {
if (curr->val == val) {
prev->next = curr->next;
delete curr;
curr = prev->next;
} else {
prev = curr;
curr = curr->next;
}
}
head = dummy->next;
delete dummy;
return head;
}
void printLinkedList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
cout << curr->val << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
int n, x;
cin >> n >> x;
int* arr = new int[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
ListNode* head = createLinkedList(arr, n);
head = removeElements(head, x);
printLinkedList(head);
delete[] arr;
ListNode* curr = head;
ListNode* next = NULL;
while (curr != NULL) {
next = curr->next;
delete curr;
curr = next;
}
return 0;
}

