给你一个链表的头节点
head
和一个整数val
,请你删除链表中所有满足Node.val == val
的节点,并返回 新的头节点 。
思路1:添加哨兵位头节点,双指针遍历
思路2:把不是val的尾插到新链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->next = head;
struct ListNode* cur = head;
struct ListNode* prev = newnode;
while(cur)
{
if(cur->val == val)
{
prev->next = cur->next;
}
else
{
prev = cur;
}
cur = cur->next;
}
newhead = newnode->next;
free(newnode);
return newhead;
}
//或者
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(head == NULL)
return NULL;
struct ListNode* cur = head;
struct ListNode* prev = NULL;
while(cur)
{
if(cur->val == val)
{
struct ListNode* next = cur->next;
if(prev == NULL)
{
head = cur->next;
}
else
{
prev->next = cur->next;
}
free(cur);
cur = next;
}
else
{
prev = cur;
cur = cur->next;
}
}
return head;
}
struct ListNode* removeElements(struct ListNode* head, int val)
{
if(head == NULL)
{
return head;
}
struct ListNode* cur = head;
struct ListNode* newhead, *tail;
newhead = tail = NULL;
while(cur)
{
if(cur->val != val)
{
if(tail == NULL)
{
newhead = tail = cur;
}
else
{
tail->next = cur;
tail = tail->next;
}
cur = cur->next;
}
else
{
struct ListNode* next = cur->next;
free(cur);
cur = next;
}
}
if(tail)
tail->next = NULL;
return newhead;
}
#define _CRT_SECURE_NO_WARNINGS 1
// 移除单链表中所有值为val的元素
#include<stdio.h>
#include<stdlib.h>
typedef struct SList
{
int val;
struct SList* next;
}SLT;
SLT* CreatSLT(int* arr, int z)
{
SLT* head = NULL;
SLT* tail = NULL;
int x = 0;
for (int i = 0; i < z; i++)
{
SLT* newnode = (SLT*)malloc(sizeof(SLT));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
else
{
newnode->val = *(arr + i);
newnode->next = NULL;
}
if (head == NULL)
{
head = tail = newnode;
}
else
{
tail->next = newnode;
tail = tail->next;
}
}
return head;
}
SLT* removeElements(SLT* head, int val) {
if (head == NULL)
return NULL;
SLT* cur = head;
SLT* prev = NULL;
while (cur)
{
//如果当前节点是需要删除的节点
if (cur->val == val)
{
//首先保存下一个节点
SLT* next = cur->next;
//如果删除的为头节点,更新头节点
//否则让当前节点的前趋节点链接next节点
if (prev == NULL)
{
head = cur->next;
}
else
{
prev->next = cur->next;
}
//释放当前节点,让cur指向next
free(cur);
cur = next;
}
else
{
//如果cur不是需要删除的节点,则更新prev,cur
prev = cur;
cur = cur->next;
}
}
return head;
}
void SLTPrint(SLT* phead)
{
SLT* cur = phead;
while (cur)
{
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
int main()
{
int arr[] = {1, 2, 6, 3, 4, 5, 6};
int val = 4;
SLT* plist = CreatSLT(arr, sizeof(arr)/sizeof(arr[0]));
SLTPrint(plist);
SLT* result = removeElements(plist, val);
SLTPrint(result);
return 0;
}