【LeetCode】203. 移除链表元素
发布时间:2024年01月17日
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);
cur = NULL;
if (prev) {
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;
ListNode* tail = newhead;
ListNode* cur = head;
while (cur != NULL) {
if (cur->val != val) {
tail->next = cur;
tail = tail->next;
cur = cur->next;
}
else {
ListNode* next = cur->next;
free(cur);
cur = next;
}
}
tail->next = NULL;
ListNode* tmp = newhead;
newhead = newhead->next;
free(tmp);
return newhead;
}
return head;
}
文章来源:https://blog.csdn.net/m0_52602233/article/details/135659795
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!