【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;
}
相关推荐
江畔柳前堤2 小时前
Function Calling 与 Tool Calling:从认知到工程的全景深度解析
开发语言·网络·人工智能·深度学习·算法·机器学习·php
Navigator_Z2 小时前
LeetCode //C - 1192. Critical Connections in a Network
c语言·算法·leetcode
zander2583 小时前
LeetCode 739:每日温度——为什么单调栈要持续弹出
开发语言·python·算法
2601_955759883 小时前
如何降低 Claude API 批量生产返工率
大数据·人工智能·算法
rannn_1113 小时前
【力扣hot100】链表专题下|138、148、23、146
java·算法·leetcode·链表·开发
ly76893 小时前
分布式一致性算法详解:从 2PC、3PC 到 Paxos、Raft、ZAB
分布式·算法
(initial)3 小时前
C-05. Kernel Fusion 代价边界:少写回 vs 寄存器压力与 occupancy
c语言·开发语言·cuda
阿维的博客日记4 小时前
保姆级教程-BBPE分词算法
算法·bbpe
不会就选b4 小时前
算法日常・每日刷题--<优先级队列>2
数据结构·算法
hanlin034 小时前
刷题笔记:力扣第189题-轮转数组
笔记·算法·leetcode