LeetCode | 203. 移除链表元素

简介: LeetCode | 203. 移除链表元素

LeetCode | 203. 移除链表元素

OJ链接

  • 这个题我们有两个思路,我们先来看第一个思路~~

思路一:

  • 当cur不等于6就一直找,找到了6就删除,但是能不能直接删除?不能,直接free了就找不到下一个了
  • 这个时候我们就要定义next指针,和prev指针,next指针保存cur的下一个地址,prev保存cur的前一个地址

代码如下:

struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* prev = NULL;
    struct ListNode* cur=head;
    while(cur != NULL)
    {
        if(cur->val == val)
        {
            struct ListNode* next = cur->next;
            free(cur);
            if(prev)
                prev->next = next;
            else
                head = next;
            cur = next;
        }
        else
        {
            prev = cur;
            cur = cur->next;
        }
    }
    return head;
}

思路二:

  • 遍历链表
  • 把不是val的节点,尾插到新链表

代码如下:

struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* newHead,*newTail;
    newHead = newTail = NULL;
    struct ListNode* pcur = head;
    while(pcur)
    {
        if(pcur->val != val)
        {
            if(newHead == NULL)
            {
                newHead = newTail = pcur;
            }
            else
            {
                newTail->next = pcur;
                newTail = newTail->next;
            }
        }
        pcur = pcur->next;
    }
    if(newTail != NULL)
        newTail->next = NULL;
    return newHead;
}
相关文章
|
5月前
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
56 1
|
5月前
Leetcode第21题(合并两个有序链表)
这篇文章介绍了如何使用非递归和递归方法解决LeetCode第21题,即合并两个有序链表的问题。
78 0
Leetcode第21题(合并两个有序链表)
|
5月前
【LeetCode 27】347.前k个高频元素
【LeetCode 27】347.前k个高频元素
59 0
|
5月前
LeetCode第二十四题(两两交换链表中的节点)
这篇文章介绍了LeetCode第24题的解法,即如何通过使用三个指针(preNode, curNode, curNextNode)来两两交换链表中的节点,并提供了详细的代码实现。
52 0
LeetCode第二十四题(两两交换链表中的节点)
|
5月前
Leetcode第十九题(删除链表的倒数第N个节点)
LeetCode第19题要求删除链表的倒数第N个节点,可以通过快慢指针法在一次遍历中实现。
61 0
Leetcode第十九题(删除链表的倒数第N个节点)
|
5月前
|
索引
力扣(LeetCode)数据结构练习题(3)------链表
力扣(LeetCode)数据结构练习题(3)------链表
132 0
|
5月前
【LeetCode 10】142. 环形链表 II
【LeetCode 10】142. 环形链表 II
39 0
|
5月前
【LeetCode 09】19 删除链表的倒数第 N 个结点
【LeetCode 09】19 删除链表的倒数第 N 个结点
29 0
|
5月前
【LeetCode 08】206 反转链表
【LeetCode 08】206 反转链表
27 0
|
9月前
|
存储 SQL 算法
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表