zoukankan      html  css  js  c++  java
  • [LintCode] Remove Linked List Elements 移除链表元素

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

     
    Example

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

    LeetCode上的原题,请参见我之前的博客Remove Linked List Elements

    解法一:

    class Solution {
    public:
        /**
         * @param head a ListNode
         * @param val an integer
         * @return a ListNode
         */
        ListNode *removeElements(ListNode *head, int val) {
            ListNode *dummy = new ListNode(-1), *pre = dummy;
            dummy->next = head;
            while (pre->next) {
                if (pre->next->val == val) {
                    ListNode *t = pre->next;
                    pre->next = t->next;
                    t->next = NULL;
                } else {
                    pre = pre->next;
                }
            }
            return dummy->next;
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param head a ListNode
         * @param val an integer
         * @return a ListNode
         */
        ListNode *removeElements(ListNode *head, int val) {
            if (!head) return NULL;
            head->next = removeElements(head->next, val);
            return head->val == val ? head->next : head;
        }
    };
  • 相关阅读:
    P2161 [SHOI2009]会场预约
    struts jar包
    struts
    HTML 简述
    JSP入门 分页
    JSP入门 生命周期
    JSP入门 el表达式
    JSP入门 导出文件
    JSP入门 文件上传
    自动增量字段重新从1开始的方法
  • 原文地址:https://www.cnblogs.com/grandyang/p/5645327.html
Copyright © 2011-2022 走看看