【LeetCode】203. 移除链表元素

leetcode链接 203. 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

在这里插入图片描述

#include 
#include 

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

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/d3e36d9556.html