203. Remove Linked List Elements

来源:互联网 发布:现有sql server 实例 编辑:程序博客网 时间:2024/06/06 23:50

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

问题:单链表删除值与val相等的元素

思想:注意头结点是否值等于val

/** * 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) {        if(head==null) return null;        ListNode temp=head;        while(temp.next!=null){        if(temp.next.val==val){        temp.next=temp.next.next;        }else{        temp=temp.next;        }                }        if(head.val==val) return head.next;        return head;    }}


0 0
原创粉丝点击