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;
}
相关推荐
业精于勤的牙3 小时前
浅谈:算法中的斐波那契数(二)
算法·职场和发展
不穿格子的程序员3 小时前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表
liuyao_xianhui4 小时前
寻找峰值--优选算法(二分查找法)
算法
dragoooon344 小时前
[hot100 NO.19~24]
数据结构·算法
Tony_yitao5 小时前
15.华为OD机考 - 执行任务赚积分
数据结构·算法·华为od·algorithm
C雨后彩虹6 小时前
任务总执行时长
java·数据结构·算法·华为·面试
风筝在晴天搁浅6 小时前
代码随想录 463.岛屿的周长
算法
一个不知名程序员www6 小时前
算法学习入门---priority_queue(C++)
c++·算法
TL滕7 小时前
从0开始学算法——第十八天(分治算法)
笔记·学习·算法