【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;
}
相关推荐
Funny_AI_LAB9 小时前
李飞飞联合杨立昆发表最新论文:超感知AI模型从视频中“看懂”并“预见”三维世界
人工智能·算法·语言模型·音视频
RTC老炮12 小时前
webrtc降噪-PriorSignalModelEstimator类源码分析与算法原理
算法·webrtc
草莓火锅14 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
散峰而望15 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github
摇滚侠15 小时前
StreamAPI,取出list中的name属性,返回一个新list
数据结构·list
Kuo-Teng15 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
fie888915 小时前
基于MATLAB的狼群算法实现
开发语言·算法·matlab
偷偷的卷15 小时前
【算法笔记 11】贪心策略六
笔记·算法
ZPC821016 小时前
FPGA 部署ONNX
人工智能·python·算法·机器人
_w_z_j_16 小时前
爱丽丝的人偶
算法