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;
    }
    }

  • 相关阅读:
    西安.NET俱乐部群 推广代码
    跟我学Makefile(六)
    跟我学Makefile(五)
    跟我学Makefile(四)
    跟我学Makefile(三)
    跟我学Makefile(二)
    Kconfig文件说明2
    Kconfig文件说明
    kernel内核配置说明
    makefile中ifeq与ifneq dev/null和dev/zero简介 dd命令
  • 原文地址:https://www.cnblogs.com/summer323/p/4505200.html
Copyright © 2011-2022 走看看