(lintcode)第452题删除链表中的元素

来源:互联网 发布:链家端口报买系统 编辑:程序博客网 时间:2024/06/06 01:42

要求:删除链表中等于给定值val的所有节点,样例:给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5

代码如下:

/** * 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        if(head==null)            return head;        ListNode p=head,q=head.next;        while(q!=null){            if(q.val==val){//保留头结点最后再做判断                p.next=q.next;                q=q.next;            }else{                p=p.next;                q=q.next;            }        }        if(head.val==val)//判断头结点            head=head.next;        return head;    }}


原创粉丝点击