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

    题目解答:

    这个题目非常简单,就是来删除在链表中出现的值为val的节点,并返回删除之后的链表。

    1,为链表增加一个虚拟的头结点,从而减少了很多冗余的判断条件,十分简单。

    2,代码结束时,需要注意将自己申请的那个虚拟头结点的空间释放掉。

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            ListNode *Head = new ListNode(-1);
            Head -> next = head;
            ListNode *p = Head;
            ListNode *q = Head -> next;
            while(q != NULL)
            {
                while((q != NULL) && (q -> val != val))
                {
                    p = p -> next;
                    q = q -> next;
                }
                if(q == NULL)
                {
                    break;
                }
                if(q -> val == val)
                {
                    ListNode *r = q ->next;
                    p -> next = r;
                    delete q;
                    q = r;
                }
            }
            p = Head -> next;
            delete Head;
            return p;
        }
    };

  • 相关阅读:
    1.3、python内置类型(0529)
    1.2、Python快速入门(0529)
    1.1、Python快速入门(0529)
    mini Linux制作过程(25/01)
    samba基本应用24-4及示例
    Apache+Php+Mariadb+NFS+discuz
    U盘中病毒了怎么办
    bind9安装配置
    负载均衡的实现(1)
    MySQL之优化
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5413976.html
Copyright © 2011-2022 走看看