欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode(52)-Remove Linked List Elements

程序员文章站 2022-03-24 23:20:34
题目: remove all elements from a linked list of integers that have value val. example given: 1...

题目:

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

思路:

题意:有序列表里面去掉给定的元素遍历发现相同的,就去掉,prev.next != null,发现了prev.next = prev.next.next 考虑头部满足条件的情况,那就一直删除下去 -

代码:

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