leetcode203 Remove Linked List Elements

来源:互联网 发布:劳务派遣公司软件 编辑:程序博客网 时间:2024/06/05 10:33

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

public class Solution {public ListNode removeElements(ListNode head, int val) {        ListNode VHead = new ListNode(-1);        VHead.next = head;        ListNode p = VHead;        ListNode q = head;        while(q!=null){        if(q.val==val){        p.next = p.next.next;        q = p.next;        }        else{        p  = p.next;        q = q.next;        }                }        return VHead.next;    }public static void main(String[] args) {// TODO Auto-generated method stubint[] a = {1,2,6,6,3,4,5,6};ListNode head = new ListNode(a[0]);ListNode p = head;for(int i = 1;i<a.length;i++){ListNode q = new ListNode(a[i]);p.next = q;p = q;}head = new Solution().removeElements(head, 6);p = head;while(p!=null){System.out.println(p.val);p = p.next;}}}class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}


1 0