【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;
}
相关推荐
CoderCodingNo22 分钟前
【GESP】C++五级考试大纲知识点梳理, (3-4) 链表-双向循环链表
开发语言·c++·链表
colus_SEU36 分钟前
【编译原理笔记】2.1 Programming Language Basics
c++·算法·编译原理
人工智能培训44 分钟前
大模型-去噪扩散概率模型(DDPM)采样算法详解
算法
Excuse_lighttime1 小时前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse
liu****1 小时前
笔试强训(二)
开发语言·数据结构·c++·算法·哈希算法
无限进步_1 小时前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
qq_433554541 小时前
C++ 完全背包
开发语言·c++·算法
lingran__2 小时前
算法沉淀第二天(Catching the Krug)
c++·算法
Yupureki2 小时前
从零开始的C++学习生活 8:list的入门使用
c语言·c++·学习·visual studio
im_AMBER2 小时前
杂记 15
java·开发语言·算法