【LeetCode】203. 移除链表元素

leetcode链接 203. 移除链表元素
在这里插入图片描述

#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;
}

相关推荐

  1. LeetCode203. 元素

    2024-01-18 11:00:01       56 阅读
  2. leetcode203. 元素

    2024-01-18 11:00:01       59 阅读
  3. Leetcode 203 元素

    2024-01-18 11:00:01       62 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-18 11:00:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-18 11:00:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-18 11:00:01       87 阅读
  4. Python语言-面向对象

    2024-01-18 11:00:01       96 阅读

热门阅读

  1. 机器学习在表面缺陷检测中的技术与实践

    2024-01-18 11:00:01       68 阅读
  2. Linux从入门到精通(第14章 传输文件)

    2024-01-18 11:00:01       53 阅读
  3. C++ 二元运算符重载

    2024-01-18 11:00:01       51 阅读
  4. Effective C++——尽可能使用const

    2024-01-18 11:00:01       48 阅读
  5. 初识微服务

    2024-01-18 11:00:01       56 阅读
  6. 聊聊PowerJob的Alarmable

    2024-01-18 11:00:01       40 阅读
  7. uni-app qiun-data-charts无法显示tooltip

    2024-01-18 11:00:01       47 阅读