【LeetCode】203. 移除链表元素

leetcode链接 203. 移除链表元素
在这里插入图片描述

#include <stdio.h>
#include <stdlib.h>struct ListNode {int val;struct ListNode* next;
};
typedef struct ListNode ListNode;ListNode* RemoveElements1(ListNode* head, int val) {ListNode* cur = head;ListNode* prev = NULL;ListNode* next = NULL;while (cur) {next = cur->next; // 下一个节点if (cur->val == val) {free(cur); // 1.删除cur = NULL;if (prev) { // 2.链接下一个节点prev->next = next;}else { // 没有前一个节点,说明删除的是头节点head = next;}}else {prev = cur; // 前一个节点}cur = next;}return head;
}ListNode* RemomveElements2(ListNode* head, int val) {if (head != NULL) {ListNode* newhead = (ListNode*)malloc(sizeof(ListNode)); // 哨兵位newhead->val = 0; newhead->next = head; // malloc可能开辟失败,所以有警告NULL PointerListNode* tail = newhead;ListNode* cur = head;while (cur != NULL) {if (cur->val != val) { // 向新链表newhead尾插tail->next = cur;tail = tail->next;cur = cur->next;}else { // 删除ListNode* next = cur->next;free(cur);cur = next;}}// 前面newhead malloc可能开辟失败,所以有警告NULL Pointertail->next = NULL; // 不free oj也能过,但是内存泄漏。ListNode* tmp = newhead;newhead = newhead->next;free(tmp);return newhead;}return head;
}