#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* deleteNode(struct ListNode* head, int val) {
if (head == NULL) {
return NULL;
}
if (head->val == val) {
struct ListNode *temp = head;
head = head->next;
free(temp);
return head;
}
struct ListNode *prev = head;
struct ListNode *cur = head->next;
while (cur != NULL) {
if (cur->val == val) {
prev->next = cur->next;
free(cur);
return head;
}
prev = cur;
cur = cur->next;
}
return head;
}
int main() {
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 1;
head->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->val = 2;
head->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->val = 3;
head->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->next->val = 4;
head->next->next->next->next = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next->next->next->next->val = 5;
head->next->next->next->next->next = NULL;
head = deleteNode(head, 3);
struct ListNode *cur = head;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
cur = head;
while (cur != NULL) {
struct ListNode *temp = cur;
cur = cur->next;
free(temp);
}
return 0;
}