zoukankan      html  css  js  c++  java
  • [LeetCode] Remove Linked List Elements

    Remove all elements from a linked list of integers that have value val.

    Example
    Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
    Return: 1 --> 2 --> 3 --> 4 --> 5

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

    每次遇到链表操作,树操作的时候我的大脑就会messed up. 各种考虑不周全,各种edge case 失败。

    思路分两步,第一步删除头,即比如要删除6,而链表是6->6->3->2。先把以目标6开头的链表变成不已目标开头的链表。

    第二步就便利链表,如果发现next 是目标,就把当前的next 变为next->next。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeElements(struct ListNode* head, int val) {
        struct ListNode* p = NULL;
        while (head != NULL && head->val == val) {
            head = head->next;
        }
        if (head == NULL) return NULL;
        
        p = head;
        while (p != NULL) {
            if (p->next != NULL && p->next->val == val) {
                p->next = p->next->next;
            } else {
                p = p->next;
            }
        }
        return head;
    }
  • 相关阅读:
    Gerrit配置--用户配置
    repo+manifests+git方式管理安卓代码
    FLASH OTP
    Wireshark抓包分析TCP协议
    python 批量修改图片大小
    python 文件查找 glob
    python 统计单词个数
    python 图片上添加数字源代码
    python 删除文件和文件夹
    python 程序列表
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4901754.html
Copyright © 2011-2022 走看看