dummy-----Remove Linked List Elements

来源:互联网 发布:好的数据恢复软件 编辑:程序博客网 时间:2024/06/10 00:08

Remove all elements from a linked list of integers that have value val.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    /**     * @param head a ListNode     * @param val an integer     * @return a ListNode     */    public ListNode removeElements(ListNode head, int val) {        // Write your code here        ListNode dummy  = new ListNode(0);        dummy.next = head;        head = dummy;        while(head.next!= null){            if (head.next.val==val)            head.next= head.next.next;//必须使用head.next否则无法访问前一个元素            else head = head.next;        }        return dummy.next;    }}
0 0
原创粉丝点击