【LeetCode】203. 移除链表元素

leetcode链接 203. 移除链表元素

c 复制代码
#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 Pointer
		ListNode* 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 Pointer
		tail->next = NULL; 
		// 不free oj也能过,但是内存泄漏。
		ListNode* tmp = newhead;
		newhead = newhead->next;
		free(tmp);
		return newhead;
	}
	return head;
}
相关推荐
灵感__idea3 小时前
Hello 算法:贪心的世界
前端·javascript·算法
钢琴上的汽车软件4 小时前
C 语言中const与指针:三种常见写法辨析
c语言·指针和const
ZK_H4 小时前
嵌入式c语言——关键字其6
c语言·开发语言·计算机网络·面试·职场和发展
澈2074 小时前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
ambition202425 小时前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
cmpxr_5 小时前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
qiqsevenqiqiqiqi5 小时前
前缀和差分
算法·图论
代码旅人ing5 小时前
链表算法刷题指南
数据结构·算法·链表
Yungoal5 小时前
常见 时间复杂度计算
c++·算法
6Hzlia5 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵