Leetcode算法题(移除链表中的元素)

题目如下:

思路1:创建一个新的带头链表 (newhead),遍历头结点对应的值分别于x进行比较,将不等于x的节点尾插到新的带头链表中,返回新的带头链表的下一个节点。

代码如下:

复制代码
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {
    ListNode* newhead, * newtail;
    newhead = newtail = (ListNode*)malloc(sizeof(ListNode));
    while (head)
    {
        if (head->val != val)
        {
            newtail->next = head;
            head = head->next;
            newtail = newtail->next;
        }
        else {
            head = head->next;
        }
    }
    newtail->next = NULL;
    return newhead->next;
}

思路2:与思路一类似,只不过是空链表,进行判断。

复制代码
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {
    if (head == NULL)
    {
        return NULL;
    }
    // 创建空链表
    ListNode* newhead, * newtail;
    newhead = newtail = NULL;
    while (head) {
        if (head->val != val) {
            // 空链表
            if (newhead == NULL) {
                newtail = newhead = head;
            }
            else {
                // 非空链表
                newtail->next = head;
                newtail = newtail->next;
            }
        }
        head = head->next;
    }
    if (newtail)
        newtail->next = NULL;
    return newhead;
}
相关推荐
前端炒粉16 小时前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
断剑zou天涯18 小时前
【算法笔记】窗口内最大值或最小值的更新结构
java·笔记·算法
smj2302_7968265218 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
骑着猪去兜风.20 小时前
线段树(二)
数据结构·算法
fengfuyao98521 小时前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
散峰而望21 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung21 小时前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
wyhwust1 天前
交换排序法&冒泡排序法& 选择排序法&插入排序的算法步骤
数据结构·算法·排序算法
利刃大大1 天前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
wyhwust1 天前
数组----插入一个数到有序数列中
java·数据结构·算法