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

    1.题目

    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

    2.分析

      简单的单链表按值查找并且删除节点。这里要注意的是 public ListNode removeElements(ListNode head, int val) {} 这个方法中给定的head是单链表实实在在的第一个节点,而不是附设的头结点。因此如果删除head节点,要特殊处理。

    3.代码(为了测试程序,多写了创建和打印单链表)

    public ListNode removeElements(ListNode head , int val) {
    //删除data值为val的节点
    if(head==null) return null;

    ListNode previous,current;
    previous=null;
    current=head;
    while(current!=null){
    if(current.val==val){
    if(previous==null) {
    head=current.next;
    current=current.next;
    }
    else{
    previous.next=current.next;
    current=current.next;
    }
    }
    else{
    previous=current;
    current=current.next;
    }
    }

    return head ;
    }

    public ListNode createList(ListNode head, int[] arr){
    //创建无头结点的单链表
    ListNode lastnode;
    lastnode=head;
    for(int i=0;i<arr.length;i++){
    ListNode node=new ListNode(arr[i]);
    node.next=null;
    lastnode.next=node;
    lastnode=node;
    }

    return head.next;
    }

    public void printList(ListNode head){
    //输出单链表节点的值
    ListNode current=head;
    while(current!=null){
    System.out.println(current.val);
    current=current.next;
    }
    }

  • 相关阅读:
    web单机优化
    html标签
    html基础
    jenkins api
    cobbler api
    Cobbler安装配置简单使用
    ubuntu 12.04下搭建web服务器(MySQL+PHP+Apache) 教程
    在ubuntu12.04上安装6款顶级漂亮的BURG主题
    Setting up an OpenGL development environment in ubuntu
    c++ list 容器
  • 原文地址:https://www.cnblogs.com/summer323/p/4505200.html
Copyright © 2011-2022 走看看