203. Remove Linked List Elements

来源:互联网 发布:出肉走淘宝 编辑:程序博客网 时间:2024/06/02 11:32

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

思路:判断p.next.val等不等于val等于的话就p.next=p.next.next;

代码如下(已通过leetcode)

public class Solution {
   public ListNode removeElements(ListNode head, int val) {
    while(head!=null && head.val==val) head=head.next;
    ListNode p=head;
    if(p==null) return null;
       while(p!=null&&p.next!=null) {
       
        if(p.next.val==val) {
        if(p.next.next==null) p.next=null;
        else p.next=p.next.next;
       
        else p=p.next;
       }
       return head;
   }
   
}

0 0
原创粉丝点击