zoukankan      html  css  js  c++  java
  • Leetcode 203. Remove Linked List Elements

    203. Remove Linked List Elements

    • Total Accepted: 71491
    • Total Submissions: 242394
    • Difficulty: Easy

    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.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* removeElements(ListNode* head, int val) {
    12         if(head==NULL) return NULL;
    13         head->next=removeElements(head->next,val);
    14         return head->val==val?head->next:head;
    15     }
    16 };

    非递归做法:

     1 class Solution {
     2 public:
     3     ListNode* removeElements(ListNode* head, int val) {
     4         ListNode *front=new ListNode(val),*end;
     5         front->next=head;
     6         end=head;
     7         head=front;
     8         while(end){
     9             if(end->val==val){
    10                 front->next=end->next;
    11             }
    12             else{
    13                 front=end;
    14             }
    15             end=front->next;
    16         }
    17         return head->next;
    18     }
    19 };
  • 相关阅读:
    kubuntu设置
    odoo git环境搭建
    ubuntu Gnome 14.10添加打印机
    ubuntu 14.10安装Balsamiq Mockups
    elementary os luna安装配置
    OpenERP QWeb模板标签笔记
    pycharm3 注册码
    统计项目代码
    odoo filter 日期
    opencart 安装
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5679325.html
Copyright © 2011-2022 走看看