zoukankan      html  css  js  c++  java
  • 删除链表中的指定元素节点

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

    Example

    Given 1->2->3->3->4->5->3, val = 3, you should return the list as1->2->4->5

    要注意开始的节点是否是要删除节点,还有中间有连续的待删除节点,和最后的节点需要删除情况

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        /**
         * @param head a ListNode
         * @param val an integer
         * @return a ListNode
         */
        ListNode *removeElements(ListNode *head, int val) {
            // Write your code here
            if(head == NULL )return NULL;
            while(head != NULL && head->val == val)
            {
                head = head->next;
            }
            if(head == NULL )return NULL;
            ListNode *p = head;
            while(p->next != NULL)
            {
                if(p->next->val != val)
                p = p->next;
                else
                {
                    ListNode *tmp = p->next;
                    while(tmp != NULL && tmp->val == val)
                    {
                        tmp = tmp->next;
                    }
                    p->next = tmp;
                    p = p->next;
                }
                if(p == NULL)break;
            }
            return head;
            
        }
    };
  • 相关阅读:
    CodeForces
    网络流
    poj 2185
    树的分治学习
    数位DP
    URAL 1969. Hong Kong Tram
    hdu 4759 Poker Shuffle
    hdu3712 Detector Placement
    分块思想
    莫比乌斯反演
  • 原文地址:https://www.cnblogs.com/dynas/p/7003821.html
Copyright © 2011-2022 走看看