【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;
}
相关推荐
尼尔森系4 小时前
排序与算法:希尔排序
c语言·算法·排序算法
AC使者4 小时前
A. C05.L08.贪心算法入门
算法·贪心算法
冠位观测者4 小时前
【Leetcode 每日一题】624. 数组列表中的最大距离
数据结构·算法·leetcode
sushang~5 小时前
leetcode203.移除链表元素
数据结构·链表
yadanuof5 小时前
leetcode hot100 滑动窗口&子串
算法·leetcode
可爱de艺艺5 小时前
Go入门之函数
算法
GEEK.攻城狮5 小时前
使用VSCODE开发C语言程序
c语言·ide·vscode
武乐乐~5 小时前
欢乐力扣:旋转图像
算法·leetcode·职场和发展
Victoria.a5 小时前
数组和指针常见笔试题(深度剖析)
c语言·开发语言
a_j585 小时前
算法与数据结构(子集)
数据结构·算法·leetcode