• 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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeElements(ListNode head, int val) {
            ListNode h = new ListNode(0);
            h.next = head;
            ListNode pre = h;
            ListNode p = head;
            while(p!=null) {
                if(p.val==val) {
                    pre.next = p.next;
                    p = p.next;
                }
                else {
                   pre = pre.next;
                   p = p.next;  
                }
            }
            return h.next;
        }
    }
  • 相关阅读:
    POJ 1061
    hihocoder 1330
    HDU 1525
    UVALive 3938
    POJ 2528
    HDU 1754
    《ACM-ICPC程序设计系列 数论及其应用》例题个人答案记录
    URAL 1277
    HDU 3746
    HDU 2087
  • 原文地址:https://www.cnblogs.com/mrpod2g/p/4451765.html
Copyright © 2020-2023  润新知