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

    https://leetcode.com/problems/remove-linked-list-elements/

    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

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

     1 public class Solution {
     2     public static ListNode removeElements(ListNode head, int val) {
     3     while(head!=null&&head.val==val){head=head.next;}
     4     if(head==null){return null;}
     5     ListNode pre_li=head;
     6     ListNode li=head.next;
     7     while(li!=null){
     8         if(li.val==val){pre_li.next=li.next;li=li.next;}
     9         else{pre_li=li;li=li.next;}
    10     }
    11     return head;
    12     }
    13     public static class ListNode {
    14     int val;
    15     ListNode next;
    16 
    17     ListNode(int x) {
    18         val = x;
    19     }
    20     }
    21     public static void main(String[]args){
    22     ListNode[]node=new ListNode[4];
    23     for(int i=0;i<node.length;i++){
    24         node[i]=new ListNode(1);
    25     }
    26     node[0].next=node[1];
    27     node[1].next=node[2];
    28     node[2].next=node[3];
    29     ListNode head=removeElements(node[0],1);
    30     while(head!=null){
    31         System.out.println(head.val);
    32         head=head.next;
    33     }
    34     }
    35 }
  • 相关阅读:
    HDU4611+数学
    HDU4612+Tarjan缩点+BFS求树的直径
    HDU4602+推导公式
    HDU4607+BFS
    HDU1353+贪心
    HDU4545+LCS
    HDU4548+素数
    HDU4539+状态压缩DP
    HDU2110+母函数
    HDU1569+最大点权集
  • 原文地址:https://www.cnblogs.com/qq1029579233/p/4478026.html
Copyright © 2011-2022 走看看