LeetCode-Remove Linked List Elements

Posted IncredibleThings

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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 dummy=new ListNode(0);
        dummy.next=head;
        ListNode p=dummy;
        while(p.next != null){
            if(p.next.val == val){
                ListNode temp=p.next;
                p.next=temp.next;
            }
            else{
                p=p.next;
            }
        }
        return dummy.next;
    }
}

 

以上是关于LeetCode-Remove Linked List Elements的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Remove Invalid Parentheses

leetcode-Remove Duplicates from Sorted Array

LeetCode-Remove Duplicates from Sorted Array II

leetcode-Remove Duplicates from Sorted List II

leetcode-Remove Duplicates from Sorted Array II-80

206. Reverse Linked List