1.给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
例如:输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
//方法1
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* prev = NULL;
struct ListNode* cur = head;
while (cur)
{
if (cur->val == val)
{
//头删
if (cur == head)
//if(prev==NULL)
{
head = cur->next;
free(cur);
cur = head;
}
else
{
//删除
prev->next = cur->next;
free(cur);
cur = prev->next;
}
}
else
{
prev = cur;
cur = cur->next;
}
}
return head;
}
//方法2
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* tail = NULL;
struct ListNode* cur = head;
head = NULL;
while (cur)
{
if (cur->val == val)
{
struct ListNode* del = cur;
cur = cur->next;
free(del);
}
else
{
//尾插
if (tail == NULL)
{
head = tail = cur;
}
else
{
tail->next = cur;
tail = tail->next;
}
cur = cur->next;
}
}
if(tail)
tail->next = NULL;
return head;
}
//方法3
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* tail = NULL;
struct ListNode* cur = head;
//哨兵位的头结点
head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next = NULL;
while (cur)
{
if (cur->val == val)
{
struct ListNode* del = cur;
cur = cur->next;
free(del);
}
else
{
tail->next = cur;
tail = tail->next;
cur = cur->next;
}
}
tail->next = NULL;
struct ListNode* del = haed;
head = head->next;
free(del);
return head;
}
2.给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
例如:输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
//方法1
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* newhead = NULL;
struct ListNode* cur = head;
while (cur)
{
struct ListNode* next = cur->next;
//头插
cur->next = newhead;
newhead